Skip to content
Justice Tech School

Properties, Getters and Setters

Properties have automatic getters and setters. Add custom ones when needed.

Example
class User(var name: String) {
    var age = 0
        set(v) { field = if (v < 0) 0 else v }
    val label get() = "$name ($age)"
}
val u = User("Ada")
u.age = -5
println(u.label)

Exercise

Backing field.

set(v) {  = v }

Quiz Test

What is field?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.