The 'also' function in Kotlin is a useful scope function that allows you to perform additional operations on an object while keeping the object itself unchanged. This is particularly helpful when you want to execute some side effects (like logging or modifying properties) without altering the flow of your code. It returns the original object, making it easy to chain operations.
val person = Person("John", 25)
val updatedPerson = person.also {
println("Updating person: ${it.name}, Age: ${it.age}")
it.age += 1 // Simulating an update to the person's age
}
println("Updated person: ${updatedPerson.name}, Age: ${updatedPerson.age}")