Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1887
心在旅途
心在旅途 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 <T> 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.

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

    My answer is totally a copy cat from the others. However, I cannot understand their expression easily. So I guess it would be nice to provide an more understandable answer.

    In swift:

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

    In Kotlin:

    b.val?.let{a -> 
      //use "a" as unwrapped
    } ?: run{
      //else case
    }
    
    0 讨论(0)
  • 2020-12-02 08:25

    we can get the same Unwraping syntax like Swift if let using inline fun

    inline fun <T:Any?> T?.unwrap(callback: (T)-> Unit) : Boolean {
        return if (this != null) {
            this?.let(callback)
            true
        }else {
            false
        }
    }
    

    Uses: :

            val  name : String? = null
            val  rollNo : String? = ""
            var namesList: ArrayList<String>?  = null
    
            if (name.unwrap { name ->
    
                    Log.i("Dhiru", "Name have value on it  $name")
    
                })else if ( rollNo.unwrap {
                    Log.i("Dhiru","Roll have value on it")
    
                }) else if (namesList.unwrap {  namesList  ->
                    Log.i("Dhiru","This is Called when names list have value ")
                })  {
                 Log.i("Dhiru","No Field have value on it ")
            }
    
    0 讨论(0)
  • 2020-12-02 08:26

    The cleanest option in my opinion is this

    Swift:

    if let a = b.val {
    
    } else {
    
    }
    

    Kotlin

    b.val.also { a ->
    
    } ?: run {
    
    }
    
    0 讨论(0)
  • 2020-12-02 08:28

    if let statement.

    Swift's Optional Binding (so called if-let statement) is used to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. So, an Optional Binding for the if-let statement is as follows:

    Swift's if-let statement:

    let b: Int? = 50
    
    if let a: Int = b {
        print("Good news!")
    } else {
        print("Equal to 'nil' or not set")
    }
    
    /*  RESULT: Good news!  */
    

    In Kotlin, like in Swift, to avoid crashes caused by trying to access a null value when it’s not expected, a specific syntax (like b.let { } in second example) is provided for properly unwrapping nullable types:

    Kotlin equivalent 1 of Swift's if-let statement:

    val b: Int? = null
    val a = b
    
    if (a != null) { 
        println("Good news!")
    } else { 
        println("Equal to 'null' or not set")
    }
    
    /*  RESULT: Equal to 'null' or not set  */
    

    Kotlin’s let function, when used in combination with the safe-call operator ?:, provides a concise way to handle nullable expressions.

    Kotlin equivalent 2 (Inline let function and Elvis Operator) of Swift's if-let statement:

    val b: Int? = null
    
    val a = b.let { nonNullable -> nonNullable } ?: "Equal to 'null' or not set"
    println(a)
    
    /*  RESULT: Equal to 'null' or not set  */
    


    guard let statement.

    guard-let statement in Swift is simple and powerful. It checks for some condition and if it evaluates to be false, then the else statement executes which normally will exit a method.

    Let's explore a Swift's guard-let statement:

    let b: Int? = nil
    
    func method() {
        guard let a: Int = b else {
            print("Equal to 'nil' or not set")
            return
        }
        print("Good news!")
    }
    method()
    
    /*  RESULT: Equal to 'nil' or not set  */
    

    Kotlin's similar effect of Swift's guard-let statement:

    Unlike Swift, in Kotlin, there is no guard statement at all. However, you can use the Elvis Operator?: for getting a similar effect.

    val b: Int? = 50
    
    fun method() {
        val a = b ?: return println("Equal to 'null' or not set")
        return println("Good news!")
    }
    method()
    
    /*  RESULT: Good news!  */
    
    0 讨论(0)
  • 2020-12-02 08:30

    You can use the let-function like this:

    val a = b?.let {
        // If b is not null.
    } ?: run {
        // If b is null.
    }
    

    Note that you need to call the run function only if you need a block of code. You can remove the run-block if you only have a oneliner after the elvis-operator (?:).

    Be aware that the run block will be evaluated either if b is null, or if the let-block evaluates to null.

    Because of this, you usually want just an if expression.

    val a = if (b == null) {
        // ...
    } else {
        // ...
    }
    

    In this case, the else-block will only be evaluated if b is not null.

    0 讨论(0)
提交回复
热议问题