Created
December 6, 2010 10:17
-
-
Save etorreborre/730097 to your computer and use it in GitHub Desktop.
An implicit pearl in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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