Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Created December 6, 2010 10:17
Show Gist options
  • Save etorreborre/730097 to your computer and use it in GitHub Desktop.
Save etorreborre/730097 to your computer and use it in GitHub Desktop.
An implicit pearl in Scala
/**
* An answer from Jason Zaugg on the scala-internals mailing list
*
* Implicit parameters can have defaults.
*/
scala> implicit def OptionalImplicit[A <: AnyRef](implicit a: A = null) = Option(a)
OptionalImplicit: [A <: AnyRef](implicit a: A)Option[A]
scala> implicitly[Option[Ordering[Int]]]
res0: Option[Ordering[Int]] = Some(scala.math.Ordering$Int$@1443628)
scala> implicitly[Option[Ordering[Any]]]
res1: Option[Ordering[Any]] = None
/**
* A variation on the theme, proposed here: http://stackoverflow.com/questions/4364601/adding-a-validity-check-dependent-on-a-typeclass
*/
class My2Col[A](a1 : A, a2 : A)(implicit num: Numeric[A] = null){
for{check <- Option(num); if(check.gteq(a1, a2))}
throw new IllegalArgumentException
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment