Konrad
Konrad

Reputation: 103

Kotlin equivalent for Optional::map in Java8

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

Answers (3)

Grzegorz Piwowarek
Grzegorz Piwowarek

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

user2340612
user2340612

Reputation: 10704

You can try with let (link to documentation):

x?.let(SomeClass::f)

Example

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

developer_hatch
developer_hatch

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

Related Questions