Created
August 2, 2016 22:28
-
-
Save malcolmgreaves/f68a38ecb37b1725de888665f1c66535 to your computer and use it in GitHub Desktop.
Nullable is a class whose type safety is _intentionally_ compromised for the sake of efficiency on the JVM.
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
import scala.language.implicitConversions | |
/** | |
* SPECIAL SEMANTICS - USE WITH CAUTION | |
* | |
* Nullable is a class whose type safety is _intentionally_ compromised. In | |
* performance-critical code, we do not want to allocate an Option wrapper | |
* around our value of type T. Here we use an extension of AnyVal to ensure | |
* we do not allocate and provide inlined helper functions to check the | |
* underlying value's nullity. | |
* | |
* To use, consider the following example code: | |
* ``` | |
* val x: T = functionThatEvaluatesToAPossibleNullOrT(...) | |
* import Nullable.Implicits._ | |
* if(x nonEmpty) | |
* // x is a valid instance of type T | |
* else | |
* // x is null | |
* ``` | |
* | |
*/ | |
final class Nullable[T](val value: T) extends AnyVal { | |
@inline def isEmpty: Boolean = | |
null == value | |
@inline def nonEmpty: Boolean = | |
!isEmpty | |
@inline def get: Option[T] = | |
Option(value) | |
} | |
object Nullable { | |
def apply[T](value: T): Nullable[T] = new Nullable[T](value) | |
def empty[T]: Nullable[T] = new Nullable[T](null.asInstanceOf[T]) | |
object Implicits { | |
@inline implicit def toNullable[T](value: T): Nullable[T] = Nullable(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment