Created
October 2, 2023 13:01
-
-
Save andiogenes/e7cafdc3593208939cb40ec548f3ddc3 to your computer and use it in GitHub Desktop.
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
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