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.
Practice
also function do in Kotlin?Solution
Step 1: Understand the purpose of
Thealsoalsofunction is used to run some extra code on an object without changing it.Step 2: Check the return value of
It returns the original object, not a transformed copy.alsoFinal Answer:
Runs extra code on an object and returns the original object -> Option AQuick Check:
alsoreturns original object [OK]
- Thinking it returns a transformed object
- Confusing it with map or let
- Assuming it stops program execution
also with a variable num in Kotlin?Solution
Step 1: Recall the syntax of
Thealsoalsofunction is called on an object with a lambda block:object.also { ... }.Step 2: Check each option for correct syntax
num.also { println(it) } uses the correct dot call and lambda syntax. Options A, C, and D have syntax errors or wrong usage.Final Answer:
num.also { println(it) } -> Option DQuick Check:
Correctalsosyntax uses dot and lambda [OK]
- Calling also as a standalone function
- Missing curly braces for lambda
- Using arrow without lambda properly
val list = mutableListOf(1, 2, 3)
val result = list.also { it.add(4) }
println(result)Solution
Step 1: Understand what
Thealsodoes herealsoblock adds 4 to the mutable list. Since the list is mutable, it changes the original list.Step 2: Check the returned value
alsoreturns the original list, now modified with 4 added.Final Answer:
[1, 2, 3, 4] -> Option CQuick Check:
also returns original object after modification [OK]
- Thinking also returns a new list
- Ignoring that list is mutable
- Expecting original list without 4
also:val text = "Hello"
text.also { it = it + " World" }
println(text)Solution
Step 1: Analyze the lambda parameter 'it'
Inalso, 'it' is a val (read-only), so you cannot reassign it inside the lambda.Step 2: Check the code for reassignment
The code tries to doit = it + " World", which is illegal and causes a compilation error.Final Answer:
Cannot reassign 'it' inside also lambda -> Option BQuick Check:
Lambda parameter 'it' is read-only [OK]
- Trying to reassign 'it' inside lambda
- Confusing also with let for transformations
- Ignoring immutability of lambda parameters
also to log each name while returning the original list unchanged?val users = listOf("Alice", "Bob", "Carol")
// Insert code here
println(users)Solution
Step 1: Understand the goal
We want to log each name but keep the original list unchanged and returned.Step 2: Check each option's behavior
users.also { it.forEach { name -> println(name) } } usesalsoto run logging side effects and returns the original list. Options B and C return transformed or Unit types, and D returns Unit.Final Answer:
users.also { it.forEach { name -> println(name) } } -> Option AQuick Check:
also runs side effects and returns original object [OK]
- Using map which changes the list
- Using let which returns last lambda result
- Using forEach alone which returns Unit
Ready to prove it?
Pass the test and this pattern moves unknown
