Kotlin equivalent for Optional::map in Java8

﹥>﹥吖頭↗ 提交于 2019-12-10 18:43:52

问题


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)

回答1:


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:




回答2:


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)



回答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


来源:https://stackoverflow.com/questions/48466390/kotlin-equivalent-for-optionalmap-in-java8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!