let keyword in kotlin code example
Example 1: let keyword in kotlin
let takes the object it is invoked upon as the parameter and returns the result of the lambda expression.
fun main(args: Array<String>) {
var str = "Hello World"
str.let { println("$it!!") }
println(str)
}
The 'it' keyword contains the copy of the property inside let. In this case "Hello world"
//This prints:
//Hello World!!
//Hello World
Example 2: let keyword in kotlin
let can be used to check null expressions.
fun main(args: Array<String>) {
var name : String? = "Kotlin let null check"
name?.let { println(it) } //prints Kotlin let null check
name = null
name?.let { println(it) } //nothing happens
}
//The code inside is executed only when the property is not null.