A quick introduction to accessors (getters and setters) in Kotlin, default accessors, custom accessors, andΒ val
Β vs.Β var
Β in the context of properties.
When not specified, default getters and setters (i.e. return field
and field = value
) are automatically generated by the compiler. Kotlin also adds syntactic sugar that allows working with properties as if they were fields, so obj.x
is actually obj.getX()
and obj.x = y
is actually obj.setX(y)
. It is important to remember that this is only syntactic sugar, and it is the accessor functions that actually get called.
If you need to customize the accessors, use get()
and/or set()
:
class FullName(var firstName: String, var lastName: String) { var stringRepresentation: String // Accessors are just regular functions, so we can use either // expression syntax or { } to define them get() = "First name is '$firstName', last name is '$lastName'" set(value) { // If no ' ' is found, assume whatever is passed // in is lastName firstName = value.substringBefore(" ", "") lastName = value.substringAfter(" ") } } fun main() { val fullName = FullName("James", "Bond") // // prints "First name is 'James', last name is 'Bond'" println(fullName.stringRepresentation) fullName.stringRepresentation = "Ferdinand von Zeppelin" // prints "First name is 'Ferdinand', last name is 'von Zeppelin'" println(fullName.stringRepresentation) }
Equipped with this knowledge, we can state the technical difference between properties defined usingΒ val
Β orΒ var
:Β val
Β doesn't generate a setter, whileΒ var
Β does.