Created
September 9, 2011 23:22
-
-
Save chrislewis/1207589 to your computer and use it in GitHub Desktop.
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
trait Zero[+A] { | |
val zero: A | |
} | |
implicit object IntZero extends Zero[Int] { | |
val zero = 0 | |
} | |
implicit def ListZero[A](implicit ev: Zero[A]) = | |
new Zero[List[A]] { val zero = Nil } | |
// utility | |
def optional[A](a: A)(implicit ev: Zero[A]) = | |
if(a == ev.zero) None else Some(a) | |
// pimp | |
class ZeroPimp[A](a:A)(implicit ev: Zero[A]) { | |
def optional(implicit ev: Zero[A]) = | |
if(a == ev.zero) None else Some(a) | |
} | |
implicit def zp[A](a: A)(implicit ev: Zero[A]) = new ZeroPimp(a) | |
/* | |
scala> 0.optional | |
res9: Option[Int] = None | |
scala> 1.optional | |
res10: Option[Int] = Some(1) | |
scala> Nil.optional | |
<console>:21: error: could not find implicit value for parameter ev: Zero[object Nil] | |
Nil.optional | |
^ | |
scala> List(0).optional | |
res12: Option[List[Int]] = Some(List(0)) | |
scala> List[Int]().optional | |
res13: Option[List[Int]] = None | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment