Created
May 6, 2024 19:55
-
-
Save Flexicon/5ea6d18b65f311aa29a01467feeed6c2 to your computer and use it in GitHub Desktop.
A simple Option Monad implementation in Kotlin
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
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