Skip to content

Instantly share code, notes, and snippets.

@andiogenes
Created October 2, 2023 13:01
Show Gist options
  • Save andiogenes/e7cafdc3593208939cb40ec548f3ddc3 to your computer and use it in GitHub Desktop.
Save andiogenes/e7cafdc3593208939cb40ec548f3ddc3 to your computer and use it in GitHub Desktop.
final class AnyRefOption[T >: Null <: AnyRef] private(private val value: T) extends AnyVal {
def isEmpty = value == null
def isDefined: Boolean = !isEmpty
def get: T = value
def foreach[U](fn: T => U): Unit = {
if (isDefined) fn(value)
}
def let[U](fn: T => U) = if (isDefined) fn(value) else AnyRefOption(null)
def also[U](fn: T => U): T = if (isDefined) {
fn(value)
value
} else value
}
object AnyRefOption {
def apply[T >: Null <: AnyRef](value: T): AnyRefOption[T] = new AnyRefOption[T](value)
object NonNull {
def unapply[T >: Null <: AnyRef](opt: AnyRefOption[T]) = opt
}
object Null {
def unapply[T >: Null <: AnyRef](opt: AnyRefOption[T]) = opt.isEmpty
}
implicit class ext[T >: Null <: AnyRef](val self: T) extends AnyVal {
def toOption: AnyRefOption[T] = AnyRefOption(self)
def ? = toOption
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment