let and run
Operate on objects.
What Are Scope Functions?
Kotlin offers five scope functions: let, run, with, apply, and also. They let you execute a block of code on an object inside a temporary scope.
- You refer to the object as
itorthis. - The block returns either the object itself or the lambda result.
In this lesson we focus on let and run.
The let Function
let executes a block where the object is available as it, and returns the lambda result.
It is great for running code only when a value is non-null, and for transforming a value into something else.
fun main() {
val name = "Alice"
val length = name.let {
println("Name is $it")
it.length
}
println("Length: $length")
}All lessons in this course
- let and run
- apply and also
- with
- Choosing the Right One