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:
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.let
takes the stringstr
as a parameter and calculates its length usingstr.length
.- The length is stored in the variable
length
. - The
println
statement outputs the length of the string. - The value of
length
is returned from thelet
block and assigned tostrLength
. - Then, another
let
block operates onstrLength
(the length of the string) by taking it aslength
. - It calculates the square of the length by multiplying
length * length
. - The
println
statement outputs the square of the length. - The squared length is returned from the
let
block and assigned tosquaredLength
. - Finally, the program prints the final squared length.