Created
April 20, 2015 15:10
-
-
Save ghik/5e68a9074669e262a032 to your computer and use it in GitHub Desktop.
Option as value class in Scala
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
| import scala.language.implicitConversions | |
| final class Opt[+A] private(private val value: Any) extends AnyVal { | |
| def isEmpty = value == null | |
| def isDefined: Boolean = !isEmpty | |
| def get: A = value.asInstanceOf[A] | |
| } | |
| object Opt { | |
| def apply[T](value: T): Opt[T] = new Opt[T](value) | |
| def unapply[T](opt: Opt[T]) = opt | |
| final val Empty: Opt[Nothing] = new Opt(null) | |
| def empty[T]: Opt[T] = Empty | |
| private val nullFunc: Any => Null = _ => null | |
| implicit def optOps[A](opt: Opt[A]): OptOps[A] = | |
| new OptOps(opt.get) | |
| class OptOps[A](private val optVal: A) extends AnyVal { | |
| def opt = Opt(optVal) | |
| def toOption: Option[A] = Option(optVal) | |
| } | |
| } | |
| object OptTest { | |
| def main(args: Array[String]) { | |
| val theOpt = Opt("szjet") | |
| val option = theOpt.toOption | |
| theOpt match { | |
| case Opt(whatevs) => println("There is " + whatevs) | |
| case Opt.Empty => println("There is nothing") | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment