Skip to content

Instantly share code, notes, and snippets.

@dylangrijalva
Created January 9, 2023 19:19
Show Gist options
  • Save dylangrijalva/dbb36350eadefdbef311c840332d67b1 to your computer and use it in GitHub Desktop.
Save dylangrijalva/dbb36350eadefdbef311c840332d67b1 to your computer and use it in GitHub Desktop.
Option<A> is a container for an optional value of type A. If the value of type A is present, the Option<A> is an instance of Some<A>, containing the present value of type A. If the value is absent, the Option<A> is an instance of None.
sealed interface Option<out A> {
data class Some<out B>(val value: B) : Option<B>
object None : Option<Nothing>
}
fun <A> some(value: A): Option<A> {
return Option.Some(value)
}
fun none(): Option<Nothing> {
return Option.None
}
fun <A> Option<A>.ifNone(fallbackValue: A): A {
return if (this is Option.Some) value else fallbackValue
}
fun <A, B> Option<A>.map(fa: (A) -> B): Option<B> {
return if (this is Option.Some) some(fa(value)) else none()
}
fun <A> A?.toOption(): Option<A> {
return if (this == null) none() else some(this)
}
fun <A> Option<A>.toNullable(): A? {
return if (this is Option.Some) value else null
}
inline fun <A> Option<A>.ifSome(block: (A) -> Unit) {
if (this is Option.Some) {
block(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment