0
votes

I've got following example class:

fun main(args: Array<String>) {
    var car = Car("Ford", 50, 8000)
    println(car.vendor)
    println("Speed: ${car.speed}")

    car.speed = 65 // How does it know which setter to invoke?
    println("New speed: ${car.speed}")
}

class Car(vendor: String = "Unknown", speed: Int = 0, price: Int = 0) {
    var vendor = vendor
        get() = field
        set(newVendor: String) {
            field = newVendor
         }

    var speed = speed
        get() = field
        set(speed: Int) {
            field = speed
        }

    var price = price
        get() = field
        set(newPrice: Int) {
            field = price
        }
}

When I change the speed-attribute (please see the commented line): Where does Kotlin know from, which setter-method it has actually to invoke?

There are two setter-methods within my class (speed, price) which both are named "set" and both expect an integer-value.

Is the order, in which the methods are defined, crucial?

The respective getter-/setter-methods have to be written directly after the attribute-definition? Or does it somehow work differently? If so: How?

Are the indentations just a covention? Or are the indentations needed for the compiler?

1

1 Answers

3
votes

car.speed = 65 is called Property-access syntax. It is equivalent to car.setSpeed(65).

You don't have two methods named set; you've two mutable properties speed and price both of type Int. They each have corresponding getter and setter methods; in Java Beans convention, the getter for speed would be getSpeed and the setter setSpeed(Int).

See https://kotlinlang.org/docs/reference/properties.html for more details.