kotlin let in two variables

val strLength: Int = "Hello, Kotlin".let { str ->
    val length = str.length
    println("Length of the string is: $length")
    length
}

val squaredLength: Int = strLength.let { length ->
    val squared = length * length
    println("Square of the length is: $squared")
    squared
}

println("Final squared length is: $squaredLength")

Explanation:

  1. let is used to execute a block of code on an object and returns the result of the block. Here, the string "Hello, Kotlin" is the object.
  2. let takes the string str as a parameter and calculates its length using str.length.
  3. The length is stored in the variable length.
  4. The println statement outputs the length of the string.
  5. The value of length is returned from the let block and assigned to strLength.
  6. Then, another let block operates on strLength (the length of the string) by taking it as length.
  7. It calculates the square of the length by multiplying length * length.
  8. The println statement outputs the square of the length.
  9. The squared length is returned from the let block and assigned to squaredLength.
  10. Finally, the program prints the final squared length.