also function. What will be printed when this code runs?val result = mutableListOf<Int>().also { it.add(1) it.add(2) it.add(3) } println(result)
The also function executes the block with the object as it and returns the original object. Here, elements are added to the list inside also, so result contains [1, 2, 3].
also function is used for in Kotlin.also lets you run extra code using the object as it and then returns the original object unchanged. It is useful for side effects like logging or modifying the object.
var name: String? = null val result = name.also { println(it!!.length) } println(result)
it!! means when it is null.The !! operator asserts that the value is not null. Since name is null, it!! throws a NullPointerException.
also for this purpose?also returns the original object after running the block with it.also is perfect for logging because it runs the block with the object as it and returns the original object unchanged. let returns the block result, run returns the block result, and apply returns the object but uses this as receiver.
data class Person(var name: String, var age: Int) val person = Person("Alice", 25).also { println("Also: ${it.name}") }.apply { age += 1 println("Apply: $age") } println("Final: ${person.age}")
also prints the name 'Alice'. apply increases age by 1 and prints 26. Finally, printing person.age shows 26 because the age was updated.