Created
January 30, 2014 09:06
-
-
Save oluies/8704986 to your computer and use it in GitHub Desktop.
makeOption that takes an argument 'a' and returns Some(a) if 'a' is not of type Option and 'a' itself otherwise?
This file contains hidden or 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 AsOption[T] { | |
type Out <: Option[_] | |
def apply(x: T): Out | |
} | |
trait LowPriorityAsOption { | |
implicit def wrapAsOption[T]: AsOption[T] = new AsOption[T] { type Out = Option[T]; def apply(x: T) = Some(x) } | |
} | |
object AsOption extends LowPriorityAsOption { | |
implicit def optionIsAlreadyOption[T <: Option[_]]: AsOption[T] = new AsOption[T] { type Out = T; def apply(x: T) = x } | |
def apply[T](x: T)(implicit asOpt: AsOption[T]): asOpt.Out = asOpt(x) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kevin Wright
//Later, in the REPL...
scala> val bibble = 42
bibble: Int = 42
scala> val boop = "Hi Mum!"
boop: String = Hi Mum!
scala> val yeehaw = Some(180)
yeehaw: Some[Int] = Some(180)
scala> AsOption(bibble)
res3: asOpt.Out = Some(42)
scala> AsOption(boop)
res4: asOpt.Out = Some(Hi Mum!)
scala> AsOption(yeehaw)
res5: asOpt.Out = Some(180)
Not an Any in sight!