Skip to content

Instantly share code, notes, and snippets.

@Flexicon
Created May 6, 2024 19:55
Show Gist options
  • Save Flexicon/5ea6d18b65f311aa29a01467feeed6c2 to your computer and use it in GitHub Desktop.
Save Flexicon/5ea6d18b65f311aa29a01467feeed6c2 to your computer and use it in GitHub Desktop.
A simple Option Monad implementation in Kotlin
package dev.flexicon.monads
sealed interface Option<out T> {
data class Some<T>(val value: T) : Option<T>
object None : Option<Nothing>
}
fun <T> some(value: T): Option<T> = Option.Some(value)
fun <T, R> Option<T>.flatMap(f: (T) -> Option<R>): Option<R> =
fold({ f(it) }, { it })
fun <T> Option<T>.get(): T? = fold({ it }, { null })
fun <T> Option<T>.getOrThrow(message: () -> String = { "Option is None" }): T =
fold({ it }, { throw IllegalStateException(message()) })
fun <T, R> Option<T>.fold(onSome: (T) -> R, onNone: (Option.None) -> R): R =
when (this) {
is Option.Some -> onSome(value)
is Option.None -> onNone(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment