Search code examples
kotlinpropertiesoverridingconstants

The best way to override a property as a constant in Kotlin


Kotlin provides support for property overriding. I an wondering what is the best way to override a property as a constant value.

To be more specific, assume that an abstract val property is declared in a superclass or an interface:

// In a superclass or an interface
abstract val num : Int

In its subclass there are at least 2 ways as far as I can think of to override it:

// In its subclass
override val num : Int = 0

or

// In its subclass
override val num : Int get() = 0

Besides the two, I can also do it in the Java way:

// In a superclass or an interface
abstract fun getNum() : Int

// In its subclass
override fun getNum() : Int = 0

What's the difference among the three in terms of memory and generated bytecode? Which one is the best?

Are there even better ways or patterns in Kotlin to declare properties that are to be overridden as constants?


Solution

  • There's functional difference.

    Using assignment You initialize the field when object is created:

    override val num : Int = 0
    

    This creates an implicit final backing field with value 0, and getter that always returns same value. This is generated bytecode decompiled into java:

    private final int num;
    
    public int getNum() {
       return this.num;
    }
    

    Second declaration is actually a getter override, which is also a valid way to implement property from the interface. This does not create a backing field, so your property can return different values on each call (for example method call):

    override val num : Int get() = 0
    

    Decompiled bytecode:

    public int getNum() {
       return 0;
    }