如何在 Kotlin 中使用 Getter 和 Setter?

how to use Getter and Setter in Kotlin?

我在长按后使用 googlemap 进行长纬度协调,我正在使用带有 getAdress 的城市名称 method.I 通过改造获取天气 api。 我想使用我从地图上得到的城市名称,即 statte 而不是伊斯坦布尔。

I want to write the city name I got from the coordinates instead of Istanbul here. "val weatherResponseCall = weatherApi.getWeather("istanbul", RetrofitSetup.apiKey")

How can I write the "statte" in the second picture instead of Istanbul? "statee = getAddress(latlng.latitude, latlng.longitude)"

If I write this instead of the city name, the program fails.

two parameters city and apikey and i just want to us here "var Statte"

The following code in Kotlin

class Person {
    var name: String = "defaultValue"
}
is equivalent to

class Person {
    var name: String = "defaultValue"

    // getter
    get() = field

    // setter
    set(value) {
        field = value
    }
}
When you instantiate object of the Person class and initialize the name property, it is passed to the setters parameter value and sets field to value.

val p = Person()
p.name = "jack"
Now, when you access name property of the object, you will get field because of the code get() = field.

println("${p.name}")
Here's an working example:

fun main(args: Array<String>) {

    val p = Person()
    p.name = "jack"
    println("${p.name}")
}

class Person {
    var name: String = "defaultValue"

    get() = field

    set(value) {
        field = value
    }
}
When you run the program, the output will be:

jack
This is how getters and setters work by default. However, you can change value of the property (modify value) using getters and setters.

Example: Changing value of the property
fun main(args: Array<String>) {

    val maria = Girl()
    maria.actualAge = 15
    maria.age = 15
    println("Maria: actual age = ${maria.actualAge}")
    println("Maria: pretended age = ${maria.age}")

    val angela = Girl()
    angela.actualAge = 35
    angela.age = 35
    println("Angela: actual age = ${angela.actualAge}")
    println("Angela: pretended age = ${angela.age}")
}

class Girl {
    var age: Int = 0
    get() = field
    set(value) {
        field = if (value < 18)
            18
        else if (value >= 18 && value <= 30)
            value
        else
            value-3
    }

    var actualAge: Int = 0
}
When you run the program, the output will be:

Maria: actual age = 15
Maria: pretended age = 18
Angela: actual age = 35
Angela: pretended age = 32
Here, the actualAge property works as expected.