Different Property setter for three same class objects in Kotlin

What I am trying to implement are three different temperature values depending on the city name. The following class:

class City(val name: String) {
    var degrees: Int = 0
    set(value) {
        when(this.name){
            ("Dubai") -> 30
            "Moscow" -> 5
            "Hanoi" -> 20
        }
        field = value
    }}

And main func:

fun main() {
    val firstCity = City("Dubai")
    val secondCity = City("Moscow")
    val thirdCity = City("Hanoi")
    println(firstCity.degrees) // 0
  }

Why is it set to default value 0? For Dubai it should have been 30.



Read more here: https://stackoverflow.com/questions/66273948/different-property-setter-for-three-same-class-objects-in-kotlin

Content Attribution

This content was originally published by Adam Heinrich at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: