🐦 Kotlin
Intermediate
What is takeIf in Kotlin?
Answer
takeIf returns the object itself if the predicate is true, otherwise returns null. It allows conditional processing inline without breaking a chain of calls. Example: val validAge = age.takeIf { it >= 18 } ?: throw IllegalArgumentException("Must be 18+"). The complementary function takeUnless returns the object when the predicate is false. Both are useful for guarding against invalid values in a functional style without needing an if-else block, keeping the code concise and readable in transformation chains.