Skip to content

Instantly share code, notes, and snippets.

@enil
Created September 28, 2016 08:06
Show Gist options
  • Save enil/843df75ab5372b34442246d663f5f951 to your computer and use it in GitHub Desktop.
Save enil/843df75ab5372b34442246d663f5f951 to your computer and use it in GitHub Desktop.
Map an optional value in kotlin
fun <T,U> T?.map(mapping: (T) -> U) = when (this) {
null -> null
else -> mapping(this)
}
@silmeth
Copy link

silmeth commented Jun 8, 2017

This should also work:

fun <T,U> T?.map(mapping: (T) -> U) = this?.let { mapping(it) }

And generally you can map any nullable using ?.let { /* do your mapping here */ }.

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