-
-
Save petekneller/e789582f240ebf8d3df0 to your computer and use it in GitHub Desktop.
Nullable types in Scala
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
object Nullable { | |
sealed trait NullableTag | |
type Nullable[A] = A with NullableTag | |
def nullAs[B]: Nullable[B] = | |
null.asInstanceOf[Nullable[B]] | |
implicit class ToNullable[A](val a: A) extends AnyVal { | |
def `?`: Nullable[A] = a.asInstanceOf[Nullable[A]] | |
} | |
implicit class NullableOps[A](val a: Nullable[A]) extends AnyVal { | |
def map[B](f: A => B): Nullable[B] = | |
if(a == null) { | |
nullAs[B] | |
} else | |
f(a).? | |
def flatMap[B](f: A => Nullable[B]): Nullable[B] = | |
if(a == null) | |
nullAs[B] | |
else | |
f(a).? | |
def fold[B](empty: B)(full: A => B): B = | |
if(a == null) | |
empty | |
else | |
full(a) | |
def getOrElse(empty: A): A = | |
if(a == null) | |
empty | |
else | |
a | |
} | |
} | |
object Examples { | |
import Nullable._ | |
def notNull = | |
("hi").? map (_ ++ " there") flatMap (a => if(a.length < 2) null else "dawg".?) getOrElse "dang" | |
def isNull = | |
("").? map (_ ++ "") flatMap (a => if(a.length < 2) null else "yeah".?) getOrElse "dang" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment