Skip to content

Instantly share code, notes, and snippets.

@chiroptical
Created December 18, 2022 19:17
Show Gist options
  • Save chiroptical/2b14df5e7da80d49a60873f6ab6438ab to your computer and use it in GitHub Desktop.
Save chiroptical/2b14df5e7da80d49a60873f6ab6438ab to your computer and use it in GitHub Desktop.
The maybe function in Kotlin
// 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