Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1917
心在旅途
心在旅途 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:23

    Here's my variant, limited to the very common "if not null" case.

    First of all, define this somewhere:

    inline fun  ifNotNull(obj: T?, block: (T) -> Unit) {
        if (obj != null) {
            block(obj)
        }
    }
    

    It should probably be internal, to avoid conflicts.

    Now, convert this Swift code:

    if let item = obj.item {
        doSomething(item)
    }
    

    To this Kotlin code:

    ifNotNull(obj.item) { item -> 
        doSomething(item)
    }
    

    Note that as always with blocks in Kotlin, you can drop the argument and use it:

    ifNotNull(obj.item) {
        doSomething(it)
    }
    

    But if the block is more than 1-2 lines, it's probably best to be explicit.

    This is as similar to Swift as I could find.

提交回复
热议问题