Swift "if let" statement equivalent in Kotlin


Swift "if let" is a conditional check operator to check whether a reference variable is NULL or not. This is a very useful technique to evaluate the unwrap optional value using swift language.

In Kotlin, we can't use this operator directly. Instead, we will be using "let" and "run" to evaluate the same. In the following example, we will see how to use "let" and "run" using Kotlin library class.

Example: Null Check using 'let' and 'run'

In this example, we will check whether the value of a reference variable is NULL or not. If the value of the reference variable is NULL, then the 'let' block will be executed, otherwise it will execute the 'run' block.

fun main(args: Array<String>) {
   val b="TutorialsPoint"
   val a = b?.let {
      // If b is not null
         println("First block");
   } ?: run {
         // If b is null.
         println("Second block");
   }
}

Output

In our example, we are checking whether the value of variable "b" is NULL or not. As the variable is not NULL, hence the compiler will execute the 'let' block and the corresponding output will be 'First block'.

First block

Now, let's change the value of 'b' to NULL, as shown below.

Example

fun main(args: Array<String>) {
   val b= null
   val a = b?.let {
      // If b is not null.
      println("First block");
   } ?: run {
         // If b is null.
         println("Second block");
   }
}

Output

Now the output will change to "Second block", as the compiler will execute the 'run' block.

Second block

Example: Null check using 'also' and 'run'

Null check can also be implemented in Kotlin using the 'also' function. In this example, we will see how it works. We will modify our above code and check if the value of the variable "b" is NULL or not.

fun main(args: Array<String>) {
   val b:String? = null
   b?.also{
      println("First block") // For not NULL value
   }?:run{
      println("Second block") // For NULL value
   }
}

Output

Second block

In the above example, the value of the variable is explicitly maintained as "NULL", hence we get the output "Second block". Once we modify the value of "b", then we will get the output as "First block".

fun main(args: Array<String>) {
   val b:String? = "TutorialsPoint"
   b?.also{
      println("First block")
   }?:run{
      println("Second block")
   }
}

Output

First block

Updated on: 23-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements