Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

467
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda