Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1925
心在旅途
心在旅途 2020-12-02 07:32

In Kotlin is there an equivalent to the Swift code below?

if let a = b.val {

} else {

}
14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 08:18

    There is a similar way in kotlin to achieve Swift's style if-let

    if (val a = b) {
        a.doFirst()
        a.doSecond()
    }
    

    You can also assigned multiple nullable values

    if (val name = nullableName, val age = nullableAge) {
        doSomething(name, age)
    }
    

    This kind of approach will be more suitable if the nullable values is used for more than 1 times. In my opinion, it helps from the performance aspect because the nullable value will be checked only once.

    source: Kotlin Discussion

提交回复
热议问题