val result = "Hello".run { val upper = this.uppercase() also { println("Inside also: $it") } lowercase() } println(result)
The run function uses the string as this. Inside, upper is the uppercase version but not returned. The also lambda prints the original string it which is "Hello". Finally, lowercase() is the last expression and returned by run. So the printed lines are:
Inside also: Hello
hello
val list = mutableListOf(1, 2, 3).apply { add(4) remove(2) } println(list)
The apply function runs the lambda on the list and returns the list itself. Inside the lambda, add(4) adds 4, and remove(2) removes the element 2. So the final list is [1, 3, 4].
val name: String? = null val length = name?.let { println("Name is not null: $it") it.length } ?: -1 println(length)
The variable name is null. The safe call name?.let { ... } skips the lambda because name is null. So the Elvis operator ?: -1 returns -1. Nothing is printed inside the lambda.
var count = 0 val result = listOf(1, 2, 3).also { count = it.sum() } println("count = $count, result = $result")
The also function runs the lambda with the list as it. Inside, count is set to the sum of the list elements (6). The also returns the original list. So the print shows count = 6 and result = [1, 2, 3].
val output = mutableListOf<String>().run { add("Start") apply { add("Middle") also { add("Almost End") } } add("End") this } println(output)
The run block starts with an empty mutable list. add("Start") adds "Start". Then apply adds "Middle" and inside also adds "Almost End". apply returns the list, so the chain continues. Then add("End") adds "End". Finally, run returns the list. The final list contains all four strings in order.