【问题标题】:Setter not assigning value in KotlinSetter 没有在 Kotlin 中赋值
【发布时间】:2021-02-19 19:37:54
【问题描述】:

我正在尝试做一个温度程序,它输出提供的三个城市的最低温度。如果三个城市之一的温度高于 + 57 或低于 -92,则所有三个城市都将设置默认值(莫斯科 +5,河内 +20,迪拜为 30)

但是,在 readLine 中提供这些数字 20,100,35 是行不通的。 这就是City 类的样子:

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

            } else {
                value
            }
        }}

我主要有:

val first = readLine()!!.toInt()
val second = readLine()!!.toInt()
val third = readLine()!!.toInt()
val firstCity = City("Dubai")
val secondCity = City("Moscow")
val thirdCity = City("Hanoi")
firstCity.degrees = first
secondCity.degrees = second
thirdCity.degrees = third

println(first)
println(second)
println(third)  

二传手有什么问题?为什么second 没有设置默认值?

【问题讨论】:

  • 您传递的 int 值是什么
  • 我通过了 20,100,35。
  • 所以输出应该是[20, 5, 35],因为只有莫斯科符合条件value > 57 || -92 > value
  • 您正在打印firstsecondthird,它们甚至不是setter 的结果,它们是readLine()s 的结果。所以问题是readLine()s
  • 另请注意,这里不需要短路运算符||,您可能应该只使用or

标签: kotlin


【解决方案1】:

按我的预期工作https://pl.kotl.in/otINdg8E3

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

            } else {
                value
            }
        }}


fun main() {
    val firstCity = City("Dubai")
    val secondCity = City("Moscow")
    val thirdCity = City("Hanoi")
    firstCity.degrees = 100
    secondCity.degrees = -100
    thirdCity.degrees = 6

    println(firstCity.degrees)  // prints 30
    println(secondCity.degrees) // prints 5
    println(thirdCity.degrees)  // prints 6
}

【讨论】:

  • 输出仍然不正确,因为超出范围的一个值应该将所有三个城市都设置为默认数字,即 20,30 和 5..
  • 河内,应该有 20 个
  • Hanoi 与条件不匹配,6 小于 57 且大于 -92,因此根据发布的逻辑,它只会设置传递的任何内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多