Swift 'if let' statement equivalent in Kotlin

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

    Swift if let statement in Kotlin

    The short answer is use simple IF-ELSE as by the time of this comment there is no equivalent in Kotlin LET,

        if(A.isNull()){
    // A is null
        }else{
    // A is not null
        }
    
    0 讨论(0)
  • 2020-12-02 08:12

    there are two answers above, both got a lot acceptances:

    1. str?.let{ } ?: run { }
    2. str?.also{ } ?: run { }

    Both seem to work in most of the usages, but #1 would fail in the following test:

    #2 seems better.

    0 讨论(0)
  • 2020-12-02 08:13

    I'm adding this answer to clarify the accepted answer because it's too big for a comment.

    The general pattern here is that you can use any combination of the Scope Functions available in Kotlin separated by the Elvis Operator like this:

    <nullable>?.<scope function> {
        // code if not null
    } :? <scope function> {
        // code if null
    }
    

    For example:

    val gradedStudent = student?.apply {
        grade = newGrade
    } :? with(newGrade) {
        Student().apply { grade = newGrade }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-02 08:21

    Unlike Swift, Its not necessary to unwrap the optional before using it in Kotlin. We could just check if the value is non null and the compiler tracks the information about the check you performed and allows to use it as unwrapped.

    In Swift:

    if let a = b.val {
      //use "a" as unwrapped
    } else {
    
    }
    

    In Kotlin:

    if b.val != null {
      //use "b.val" as unwrapped
    } else {
    
    }
    

    Refer Documentation: (null-safety) for more such use cases

    0 讨论(0)
  • 2020-12-02 08:23

    Here's how to only execute code when name is not null:

    var name: String? = null
    name?.let { nameUnwrapp ->
        println(nameUnwrapp)  // not printed because name was null
    }
    name = "Alex"
    name?.let { nameUnwrapp ->
        println(nameUnwrapp)  // printed "Alex"
    }
    
    0 讨论(0)
提交回复
热议问题