Created
September 28, 2016 08:06
-
-
Save enil/843df75ab5372b34442246d663f5f951 to your computer and use it in GitHub Desktop.
Map an optional value 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
fun <T,U> T?.map(mapping: (T) -> U) = when (this) { | |
null -> null | |
else -> mapping(this) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should also work:
And generally you can map any nullable using
?.let { /* do your mapping here */ }
.