Created
December 18, 2022 19:17
-
-
Save chiroptical/2b14df5e7da80d49a60873f6ab6438ab to your computer and use it in GitHub Desktop.
The maybe function in Kotlin
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
// The same behavior as the Haskell version | |
fun <T, U> T?.maybe(default: U, f: (T) -> U) = | |
when (this) { | |
null -> default | |
else -> f(this) | |
} | |
// When `f` returns null you get the default | |
fun <T, U> T?.maybeBad(default: U, f: (T) -> U) = | |
this?.let { f(it) } ?: default | |
// A less generic version where U is forced to be a non-null type. | |
fun <T, U : Any> T?.maybeOk(default: U, f: (T) -> U) = | |
this?.let { f(it) } ?: default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment