val result = "hello".let { println(it.uppercase()) it.length }.also { println(it * 2) } println(result)
The let block prints the uppercase string "HELLO" and returns the length 5.
The also block receives 5, prints 5 * 2 = 10, and returns the original receiver which is 5.
Finally, println(result) prints 5.
val builder = StringBuilder().apply { append("Hi") }.run { append(" there") toString() } println(builder)
apply appends "Hi" and returns the StringBuilder.run appends " there" and returns the string representation.
So builder is "Hi there".
val text = "abc".let { it.uppercase() }.with { println(this) length } println(text)
This code produces an error. The let block returns a String "ABC".
However, with is a top-level function that takes the receiver as its first argument, but here it is called as an extension function, which is invalid.
Therefore, the compiler reports an error: Unresolved reference: with.
val list = mutableListOf(1, 2, 3).run { add(4) also { it.removeAt(0) } size } println(list)
run returns the last expression, which is size (an Int).also returns the receiver list but is not the last expression.
After adding 4 and removing the first element, the list has 3 elements.
So list is 3.
result?val result = "Kotlin".also { println(it.lowercase()) }.let { it.length }.apply { println(this) }
also prints "kotlin" and returns the original string "Kotlin".let returns the length 6.apply is called on the integer 6 (scope functions are extensions on Any, so work on Int), prints 6, and returns the receiver 6.
Thus, result is 6.