Skip to content

Instantly share code, notes, and snippets.

@retronym
Created November 7, 2009 22:56
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 retronym/228927 to your computer and use it in GitHub Desktop.
Save retronym/228927 to your computer and use it in GitHub Desktop.
Use of generalised type constraints to implement Option.flatten
sealed trait Option[+A] {
def isDefined: Boolean
def flatten[B](implicit ev: A <:< Option[B]): Option[B]
}
case object None extends Option[Nothing] {
def isDefined = false
def flatten[B](implicit ev: Nothing <:< Option[B]): Option[B] = None
}
case class Some[A](value: A) extends Option[A] {
def isDefined = true
def flatten[B](implicit ev: A <:< Option[B]): Option[B] = value
}
println((Some(Some(1)).flatten, Some(None).flatten)) //(Some(1),None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment