Reputation: 103
Do you know if there is a shortcut for:
if (x == null) null else f(x)
For Java Optional
you can just do:
x.map(SomeClass::f)
Upvotes: 7
Views: 2321
Reputation: 13773
Kotlin utilizes its own approach to the idea of Option
, but there're map
, filter
, orElse
equivalents:
val x: Int? = 7 // ofNullable()
val result = x
?.let(SomeClass.Companion::f) // map()
?.takeIf { it != 0 } // filter()
?: 42 // orElseGet()
I ended up writing a full comparison here:
Upvotes: 16
Reputation: 10704
You can try with let
(link to documentation):
x?.let(SomeClass::f)
fun f(n: Int): Int {
return n+1
}
fun main(s: Array<String>) {
val n: Int? = null
val v: Int? = 3
println(n?.let(::f))
println(v?.let(::f))
}
This code prints:
null
4
Upvotes: 3
Reputation: 16224
You can use let in this case, like this:
fun f(x : Int) : Int{
return x+1
}
var x : Int? = 1
println(x?.let {f(it)} )
=> 2
x = null
println(x?.let {f(it)} )
=> null
and as @user2340612 mentioned, it is also the same to write:
println(x?.let(::f)
Upvotes: 3