Properties (Kotlin)

A property is a class member that holds state, declared with val or var. Kotlin properties come with auto-generated getters/setters and support custom accessors and lazy initialization.

Kotlin

Instead of fields plus getter/setter methods, Kotlin has properties. A val property gets a getter; a var property gets a getter and setter, generated automatically. You access them with dot syntax (obj.name) and the right accessor is called under the hood.

You can customize accessors: a computed property defines a custom get() with no backing field (val area get() = w * h), and a var can validate in its set(value) { ... }. The keyword field refers to the backing field inside an accessor.

Delegated properties add power: by lazy { } computes the value on first access and caches it, by Delegates.observable() fires on change, and by map reads from a map. These cover common patterns without boilerplate.

Syntax

val area: Int get() = width * height
var name: String = ""
    set(value) { field = value.trim() }

Examples

Kotlin

class Circle(val r: Double) {
    val area: Double get() = 3.14 * r * r
}
println(Circle(2.0).area)

Output:

12.56

Learn it in a lesson

See also

Back to the Dictionary