Properties — Introduction
Definition of fields, properties, getters and setters. Difference between fields and properties. Contrasting fields and properties in Java vs. Kotlin
— — — — — — — — — — — — — — —
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.
First, some definitions, so we’re all on the same page:
- when we talk about a field, we are referring to a block of memory that has a name, type, and size that corresponds to it.
- when we talk about a property, we are talking about a value that’s presented to (and possibly consumed from) a place in code.
A property may directly expose a field (a memory-backed property), or merely calculate a value or have a side effect (a synthetic property). It is customary for properties to be implemented as one or two functions.
- One function, called the getter, is used to present the value.
- The optional other function, the setter, is used to consume the value. If the setter is omitted, it’s called a read-only property.
In Java, data is stored in fields. However, Java has no syntactic mechanism to define properties. Properties in Java must be created manually, by implementing the corresponding getters/setters (and possibly a backing field).
class PublicIntField {
public int x;
}
class PublicMemoryBackedIntProperty {
private int x = 0;
public int getX() {
return x;
}
public void setX(final int newX) {
x = newX;
}
}
class PublicMemoryBackedIntReadonlyProperty {
private int x;
public PublicIntReadonlyProperty(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
class PublicBooleanSyntheticPropertyAndPublicIntField {
public Int x;
public boolean isXSet() {
return x != null;
}
}In Kotlin, the val/var keywords always declare properties, and never fields. It is not possible to declare fields directly. This might sound confusing, but bear with us, it’ll become clearer over the next few chapters.
Here’s how you would write the previous classes in Kotlin:







