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
})
}
Create a free account and build your private vault. Share publicly whenever you want.