Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

469
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda