Discover how a tiny function can save you from repeating yourself and make your code sparkle with clarity!
Why Also function behavior and use cases in Kotlin? - Purpose & Use Cases
Imagine you want to create an object and then perform some extra actions on it, like logging or modifying properties, all in one place.
Without special tools, you write separate lines for creating the object and then for each action.
This manual way means repeating the object name many times, making the code longer and harder to read.
It's easy to make mistakes or forget to do something right after creating the object.
The also function lets you do extra things with an object right after creating it, without repeating its name.
This keeps your code short, clear, and easy to follow.
val person = Person()
person.name = "Anna"
println(person.name)val person = Person().also {
it.name = "Anna"
println(it.name)
}You can cleanly add side actions or modifications to objects right where you create them, making your code neat and less error-prone.
When setting up a user profile, you create the user object and immediately log its creation or set extra details without extra lines.
also helps run extra code on an object without repeating its name.
It makes code shorter and easier to read.
Great for logging, debugging, or setting extra properties right after creation.