Skip to content

Instantly share code, notes, and snippets.

@ghik
Created April 20, 2015 15:10
Show Gist options
  • Select an option

  • Save ghik/5e68a9074669e262a032 to your computer and use it in GitHub Desktop.

Select an option

Save ghik/5e68a9074669e262a032 to your computer and use it in GitHub Desktop.
Option as value class in Scala
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