Understanding the impact of var and val with respect to getters and setters of a property

Issue

Let’s say I have a Kotlin class Dog with two properties weight and weightInKgs

class Dog(val weight: Double) {  
    // property without initializing works. Why?
    val weightinKgs: Double
    get()  weight/ 2.2;
}

The above code runs without errors. I know that every property in Kotlin must be initialized so why does defining a getter without initializing the property work? Secondly, when val is changed to var for weightInKgs, it produces an error asking for initialization. How does changing it to var break the code?

class Dog(val weight: Double) {
    // well its doesn't work now. 
    var weightinKgs: Double
        get()  weight/ 2.2;
}

Solution

Every property with a backing field must be initialized. A property has a backing field if any of the following is true:

  • You initialize the backing field at the declaration site using “.
  • It has a custom getter or setter that references field.
  • It uses the implicit getter or setter, which implicitly uses field.

Otherwise, it does not have a backing field.

If there is no backing field used by the getter and/or setter, there is no need to initialize one. Your first code block has a custom getter that doesn’t use field.

In your second code block, you have a var and it’s using the implicit setter, which uses the backing field, so the backing field must be initialized.

Answered By – Tenfour04

Leave a Comment