🏎️ · Basics

2 min read Β· Updated on by

Read on to find out about fields, properties, getters and setters. Learn about the difference between fields and properties and see understand the differences in fields and properties between Java vs. Kotlin.

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 propertiesProperties in Java must be created manually, by implementing the corresponding getters/setters (and possibly a backing field).


//sampleStart
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;
    }
}
//sampleEnd

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:


//sampleStart
// Equivalent of above. The compiler automatically generates a
// hidden backing field for both classes, which is only directly
// accessible in custom accessors (we'll get to all that in a sec).
// It also generates a default getter and setter pair.
class PublicIntProperty {
    var x: Int = 0
}

class PublicIntReadonlyProperty(val x: Int)

// To define a synthetic property, we specify the getter
// explicitelly. As a consequence, the hidden backing
// field is not generated in this case. We'll cover this
// in more detail further on.
class PublicBooleanSyntheticPropertyAndPublicIntField {
    var x: Int? = null
    
    val xSet: Boolean get() = x != null
}
//sampleEnd
fun main() {
    val poem = """
        When you're drowning in a sea of code,
        Kotlin's lifeline is a developer's ode.
        With concise syntax and expressive might,
        In the coding universe, it's the guiding light!
    """.trimIndent()
    println(poem)
}

When properties are not initialized directly, they must be initialized in the constructor:


//sampleStart
class Ten {
    val x: Int

    init {
        x = 10
    }
}
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the wizard with a bag of tricks,
        From lambdas to delegates, it clicks.
        In the world of programming, a magic show,
        With Kotlin, your code will glow!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer