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
Example
Best Practices
- Use
takeIffor concise conditional assignments. - Combine with safe-call and
let.
takeUnless
takeUnless returns the object if the condition is false, otherwise returns null.
Syntax
Example
Best Practices
- Use
takeUnlessfor negative conditions. - Improves readability over
if (!condition).
lazy
lazy initializes a property only when it is accessed for the first time.
Example
Best Practices
- Use
lazyfor expensive initialization. - Ideal for read-only (
val) properties.
lateinit
lateinit allows declaring a non-null variable without initializing it immediately.
Example
Best Practices
- Use only with
varand non-primitive types. - Ensure initialization before use to avoid runtime exceptions.
apply Usage
apply is used to configure an object and returns the object itself.
Example
Best Practices
- Use
applyfor object setup. - Avoid heavy logic inside
apply.
also Usage
also is used to perform side-effects and returns the object.
Example
Best Practices
- Use
alsofor logging and debugging. - Do not modify core logic in
also.
Comparison Summary
| FunctionContextReturn Value | ||
| takeIf | it | object/null |
| takeUnless | it | object/null |
| lazy | - | value |
| lateinit | - | variable |
| apply | this | object |
| also | it | object |
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.