Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

468
Views
Override variable in subclass in Kotlin

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!