Kotlin apply()

Kotlin apply() Function

The Kotlin apply() function is used to apply a block of code to an object.

It is often used for initializing an object or configuring its properties in a concise manner.

In this tutorial, you shall learn the syntax of apply() function, and how to use it in a program with examples.

Syntax

The syntax of apply() function is

inline fun <T> T.apply(block: T.() -> Unit): T

where

ParameterDescription
blockThe lambda function or block of code to be applied to the object.
Properties of Kotlin apply() function

Return value

The apply() function returns the receiver object after applying the provided block of code.

Example 1: Initializing an Object using apply()

In this example, we shall demonstrate how to use apply() function to set the properties of a Person object in a concise manner.

Kotlin Program


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

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

Output

Person(name=Ram, age=30)

Summary

In this tutorial, we have seen about Kotlin apply() function, its syntax, and how to use this apply() function to apply a block of code to an object with examples.