7

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)

3 Answers 3

16

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:

3

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)
0
3

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
2
  • 1
    I really don't understand why your answer has a downvote... But don't worry I think and I checked that your answer is also ok, it's a plus one (Y) Jan 26, 2018 at 17:49
  • 1
    @DamianLattenero I don't get it, too, actually! But the same applies to your answer as well :) Jan 26, 2018 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.