Created
November 7, 2009 22:56
-
-
Save retronym/228927 to your computer and use it in GitHub Desktop.
Use of generalised type constraints to implement Option.flatten
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
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