Skip to content

Instantly share code, notes, and snippets.

@pakoito
Last active January 17, 2018 16:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pakoito/91c01237217483b7be509996b243cf28 to your computer and use it in GitHub Desktop.
Save pakoito/91c01237217483b7be509996b243cf28 to your computer and use it in GitHub Desktop.
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