Home > Software design >  Override variable in subclass in Kotlin
Override variable in subclass in Kotlin

Time:03-01

I have this super class:

abstract class Node(rawId: String) {
    open val id: String
    init {
        id = Base64.toBase64(this.javaClass.simpleName   "_"   rawId)
    }
}

And this subclass that extends Node:

data class Vendor (
    override var id: String,
    val name: String,
    val description: String,
    val products: List<Product>?
): Node(id)

When I initialize the Vendor class like this:

new Vendor(vendor.getId(), vendor.getGroup().getName(), description, products);

I can see the init block in Node get fired as expected. However, when I get the id from the Vendor object, it is the rawId and not the encoded Id.

So I am a bit confused about the initialization order/logic in Kotlin classes. I want the encoding code to be common across all subclasses. Is there a better way to do it?

CodePudding user response:

The problem is because you are overriding the id field in the subclass and hence it would always remain the rawId value.

Since the base class has already an id field which has to be an encoded value, you don't need to override it in the subclass. You need to provide the rawId to the Node class in your Vendor class and let the base class take care of the id value to be instantiated with. You can have your abstract class as

abstract class Node(rawId: String) {
    val id: String = Base64.toBase64(this.javaClass.simpleName   "_"   rawId)
}

and then define your subclass as

data class Vendor (
    val rawId: String,
    val name: String,
    val description: String,
    val products: List<Product>?
): Node(rawId)

Then with

Vendor newVendor = new Vendor(vendor.getId(), vendor.getGroup().getName(), description, products);
newVendor.getId() // would be the encoded id as you expect

since Vendor is a subclass of Node, the id field is also available to the Vendor object with the encoded value.

  • Related