Skip to content

Instantly share code, notes, and snippets.

@pakoito
Last active Jan 17, 2018
Embed
What would you like to do?
Lightweight Option
inline fun <A, B> A?.fold(crossinline fn: () -> B, crossinline f: (A) -> B): B =
if (this == null) fn() else f(this)
inline fun <A, B> A?.map(crossinline f: (A) -> B): B? = fold({ null }, f)
inline fun <A> A?.orElse(crossinline fn: () -> A): A = fold(fn, { it })
@pakoito
Copy link
Author

pakoito commented Nov 16, 2017

val a: Int? = null
val x = a.map { it + 1 }.orElse { 0 }
// 0
val a: Int? = 0
val x = a.map { it + 1 }.orElse { 0 }
// 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment