Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Kotlin Dictionary

  1. Home
  2. Kotlin Dictionary
  3. apply

apply

Since: Kotlin 1.0(2016)

The Kotlin scope function apply is used to configure or initialize an object. Inside the block, you reference the object via this, and the return value is the receiver itself.

Syntax

val result = object.apply {
    // this = the object
    property = value
    method()
}
// result is the object itself

Scope Functions Overview

Scope FunctionContext ReferenceReturn ValueUse Case
apply { }this (can be omitted)Receiver itselfUsed to configure or initialize an object.
also { }itReceiver itselfUsed to insert side effects such as logging or debugging.
let { }itLambda resultUsed for null checks or transformation chains.
run { }this (can be omitted)Lambda resultCombines object setup with a computation.

Sample Code

sample_scope_apply.kt
data class Person(var name: String = "", var age: Int = 0, var email: String = "")

fun main() {
    // Initialize an object with apply (this can be omitted).
    val person = Person().apply {
        name = "Ayanami Rei"
        age = 14
        email = "ayanami_rei@wp-p.info"
    }
    println(person)
    // Person(name=Ayanami Rei, age=14, email=ayanami_rei@wp-p.info)

    // apply is also commonly used to build a StringBuilder.
    val sb = StringBuilder().apply {
        append("Hello")
        append(", ")
        append("Kotlin!")
    }
    println(sb.toString()) // Hello, Kotlin!

    // apply chaining — you can chain multiple configurations together.
    val list = mutableListOf<String>().apply {
        add("Apple")
        add("Banana")
        add("Cherry")
    }
    println(list) // [Apple, Banana, Cherry]

    val size = mutableListOf<Int>().apply {
        addAll(listOf(1, 2, 3, 4, 5))
    }.size
    println(size) // 5
}
scope_apply.kt
kotlinc scope_apply.kt -include-runtime -d scope_apply.jar
java -jar scope_apply.jar
Person(name=Ayanami Rei, age=14, email=ayanami_rei@wp-p.info)
Hello, Kotlin!
[Apple, Banana, Cherry]
5

Common Mistakes

NG example 1: Expecting apply to return the last expression — apply always returns the receiver itself

NG example 2: Using it inside apply — apply uses this, not it

NG example 3: Using apply on an object with val properties — val properties cannot be reassigned

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

fun main() {
    // The last expression inside apply is not returned — the receiver itself is returned
    val wrongResult = Character().apply {
        name = "Ayanami Rei"
        name // This value is NOT returned
    }
    println(wrongResult.name) // Ayanami Rei (a Character is returned)
}

Use run when you need the last expression as the return value

sample_scope_apply_mistakes.kt
data class Character(var name: String = "", var age: Int = 0, var series: String = "")

fun main() {
    val reiName = Character().run {
        name = "Ayanami Rei"
        name
    }
    println(reiName) // Ayanami Rei

    // Inside apply, access properties via this (this can be omitted)
    val rei = Character().apply {
        name = "Ayanami Rei"
        age = 14
        series = "Evangelion"
    }
    println(rei) // Character(name=Ayanami Rei, age=14, series=Evangelion)
}

The command looks like this:

kotlinc sample_scope_apply_mistakes.kt -include-runtime -d sample_scope_apply_mistakes.jar
java -jar sample_scope_apply_mistakes.jar
Ayanami Rei
Character(name=Ayanami Rei, age=14, series=Evangelion)

Notes

apply is commonly used as an initialization block for an object. Inside the block, the receiver is referenced via this, so you can assign to properties directly by name.

Because the return value is the receiver itself, it is convenient to assign the newly created object directly to a variable or use it as part of a method chain.

For inserting side effects, see also. For null checks, see let. When you need to return a computed result, see run / with.

If you find any errors or copyright issues, please .