Accessors
A quick introduction to accessors (getters and setters) in Kotlin, default accessors, custom accessors, and val
vs. var
in the context of properties
— — — — — — — — — — — — — — —
THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.
— — — — — — — — — — — — — — —
Tags: #KOTLIN FEATURE
This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.
It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.
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…