October 2021
Intermediate to advanced
500 pages
16h 23m
English
In Kotlin, a lambda can modify and reference variables defined outside its scope. Any variables the lambda accesses that are defined outside it are captured by the lambda, meaning that the lambda will hold a reference back to it. This was the case of the first lambda expression you used in your narrate function.
As a demonstration of this property of lambdas, add another mood to the changeNarratorMood function:
Listing 8.19 Modifying variables from a lambda (Narrator.kt)
...
fun changeNarratorMood() {
val mood: String
val modifier: (String) -> String
when (Random.nextInt(1..4)) {
when (Random.nextInt(1..5)) {
...
3 -> {
mood = "unsure"
modifier = { message ->
"$message?"
}
}
4 -> {
var ...Read now
Unlock full access