Skip to content

Instantly share code, notes, and snippets.

@oluies
Created January 30, 2014 09:06
Show Gist options
  • Save oluies/8704986 to your computer and use it in GitHub Desktop.
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?
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)
}
@oluies
Copy link
Author

oluies commented Jan 30, 2014

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment