Kotlin

apply — Configure Object, Return Itself

admin by @admin ADMIN
Jun 12, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`x.apply { ... }` runs the block with `x` as `this` (so you call methods/set properties directly) and returns `x`. The canonical builder-style configuration.
Kotlin
Raw
class Connection {
    var host: String = "localhost"
    var port: Int = 8080
    var timeoutMs: Int = 5_000
    fun connect() { println("connecting to $host:$port") }
}

fun main() {
    // Without apply — repetitive
    val c1 = Connection()
    c1.host = "api.example.com"
    c1.port = 443
    c1.timeoutMs = 30_000

    // With apply — configure inline, returns the configured object
    val c2 = Connection().apply {
        host      = "api.example.com"          // implicit `this.`
        port      = 443
        timeoutMs = 30_000
    }
    c2.connect()

    // Works great when chaining or passing as an argument
    fun useConnection(c: Connection) { c.connect() }
    useConnection(Connection().apply {
        host = "db.internal"
        port = 5432
    })
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.