Skip to content

Instantly share code, notes, and snippets.

@chrislewis
Created September 9, 2011 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislewis/1207589 to your computer and use it in GitHub Desktop.
Save chrislewis/1207589 to your computer and use it in GitHub Desktop.
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