val/var <property name>: <Type> by <expression>

Lazy Properties

val answer: Int by lazy {
    println("Computing the answer to the Ultimate Question of Life, the Universe, and Everything")
    42
}
 
println("What is the answer?")
// Will print 'Computing...' and then 42
println(answer) // 42
println("Come again?")
// Will just print 42
println(answer) // 42 

Observable Properties

  • listeners are notified about changes to this property.
  • The handler is called every time you assign to the property (after the assignment has been performed). It has three parameters: the property being assigned to, the old value, and the new value:
  • vetoable
import kotlin.properties.Delegates
 
class User {
    var name: String by Delegates.observable("<no name>") {
        prop, old, new ->
        println("$old -> $new")
    }
}
 
fun main() {
    val user = User()
    user.name = "first"
    user.name = "second"
}

Properties in Map

class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int     by map
}
 
val user = User(mapOf(
    "name" to "John Doe",
    "age"  to 25
))