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

277
Visualizações
Kotlin getter / setter when using a primary constructor

The example is from a Kotlin-course I'm doing:

class Car {
    var speed: Int = 0
        get() = field 
        set(value) {
            field = value
        }
}

If I like to use a primary constructor like this:

class Car(var speed: Int)

How would I have to write the getter / setter in that case?

over 4 years ago · Hanz Gallego
4 Respostas
Responde à pergunta

0

You can just initialize your property with the value from constructor:

class Car(speed: Int) {
    var speed: Int = speed
        get() = field
        set(value) {
            field = value
        }
}
over 4 years ago · Hanz Gallego Relatório

0

You cannot write getters/setters inside of the constructor, you can do the following:

  1. Create variable inside class whose value taken from constructor.
class Car(speed: Int) {
    var speed = speed
        get() = field 
        set(value) {
            field = value
        }
}
  1. Use @JvmField annotation to restrict compiler not to auto-generate getters/setters and implement one yourself
class Car(@JvmField private var speed: Int) {
    fun getSpeed() = speed
    fun setSpeed(value: Int) { speed = value }
}
over 4 years ago · Hanz Gallego Relatório

0

If your Car is just a data holder, you could make it a data class, which generates a bunch of methods for you, see this example:

data class Car(var speed: Int)

You can use a parameterized constructor and the setters as follows

fun main() {
    // use a parameterized constructor
    var car = Car(240)
    println("${car.speed} km/h")

    // use the setter
    car.speed = 120
    println("${car.speed} km/h")
}

That would output:

240 km/h
120 km/h
over 4 years ago · Hanz Gallego Relatório

0

Syntax of property –

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

Here, property initializer, getter and setter are optional. We can also omit property type if it can be inferred from the initializer. The syntax of a read-only or immutable property declaration differs from a mutable one in two ways: starts with val instead of var, and does not allow a setter.

In kotlin, val is used as only for read means getter and var is used as for not getter() and setter()

class Company {
var name: String = "Defaultvalue"
}

The above code is equivalent to the below code

class Company {
    var name: String = "defaultvalue"
        get() = field                     // getter
        set(value) { field = value }      // setter
}

You can also use kotlin data class if you want to hold data in your Car class. so you no need to define getter and setter.

data class Car(var speed: Int)

For more check https://kotlinlang.org/docs/reference/properties.html#getters-and-setters

over 4 years ago · Hanz Gallego 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