Kotlin Standard Library Concepts Tutorial: takeIf, takeUnless, lazy, lateinit, apply, and also


This Kotlin Standard Library Concepts tutorial explains commonly used Kotlin standard library features such as takeIf, takeUnless, lazy, lateinit, and practical usage of apply and also. These features help write concise, readable, and efficient Kotlin code, especially for object initialization, conditional logic, and deferred initialization.

Kotlin Standard Library Concepts – Complete Tutorial

takeIf

takeIf returns the object if the given condition is true, otherwise returns null.

Syntax


value.takeIf { condition }

Example


fun main() {
val number = 10
val result = number.takeIf { it > 5 }
println(result) // 10
}

Best Practices

  1. Use takeIf for concise conditional assignments.
  2. Combine with safe-call and let.

number.takeIf { it > 5 }?.let {
println("Valid number: $it")
}

takeUnless

takeUnless returns the object if the condition is false, otherwise returns null.

Syntax


value.takeUnless { condition }

Example


fun main() {
val age = 15
val result = age.takeUnless { it < 18 }
println(result) // null
}

Best Practices

  1. Use takeUnless for negative conditions.
  2. Improves readability over if (!condition).

lazy

lazy initializes a property only when it is accessed for the first time.

Example


val message: String by lazy {
println("Initialized")
"Hello Kotlin"
}

fun main() {
println(message)
println(message)
}

Best Practices

  1. Use lazy for expensive initialization.
  2. Ideal for read-only (val) properties.

lateinit

lateinit allows declaring a non-null variable without initializing it immediately.

Example


class User {
lateinit var name: String

fun initName() {
name = "Muni"
}
}

fun main() {
val user = User()
user.initName()
println(user.name)
}

Best Practices

  1. Use only with var and non-primitive types.
  2. Ensure initialization before use to avoid runtime exceptions.

apply Usage

apply is used to configure an object and returns the object itself.

Example


data class Person(var name: String = "", var age: Int = 0)

fun main() {
val person = Person().apply {
name = "Muni"
age = 35
}
println(person)
}

Best Practices

  1. Use apply for object setup.
  2. Avoid heavy logic inside apply.

also Usage

also is used to perform side-effects and returns the object.

Example


fun main() {
val list = mutableListOf(1, 2, 3)
list.also { println("Before adding: $it") }
.add(4)
println("After adding: $list")
}

Best Practices

  1. Use also for logging and debugging.
  2. Do not modify core logic in also.

Comparison Summary

FunctionContextReturn Value
takeIfitobject/null
takeUnlessitobject/null
lazy-value
lateinit-variable
applythisobject
alsoitobject

Summary

This chapter covered important Kotlin standard library concepts including takeIf, takeUnless, lazy, lateinit, and practical usage of apply and also. Mastering these features improves code readability, safety, and performance in Kotlin applications.