gpt4 book ai didi

kotlin - 检查空变量,然后在其上执行if语句

转载 作者:行者123 更新时间:2023-12-02 13:34:44 25 4
gpt4 key购买 nike

我正在学习 Kotlin 。我想知道这是解决此问题的最佳方法:
我有一堂简单的课:

class AlternativeCustomerTwo(
val name: String = "Name Not Provided",
var age: Int? = null,
var address: String = "Address not provided"
)

它具有默认参数,并且可以为空。

我要包括以下字段:
var isApproved: Boolean = false

所以现在我有一个类,看起来像:
class AlternativeCustomerTwo(
val name: String = "Name Not Provided",
var age: Int? = null,
var address: String = "Address not provided"
) {

var isApproved: Boolean = false}

现在,我想覆盖isApproved的默认 setter ,该 setter 检查年龄是否超过21岁,如果超过21岁,则将其设置为true。像这样:
class AlternativeCustomerTwo(
val name: String = "Name Not Provided",
var age: Int? = null,
var address: String = "Address not provided"
) {
var isApproved: Boolean = false
set(value) {
if(age >= 21) {
field = value
}
}
}

这里的问题是 var age 。代码无法编译,这是错误:

Error:(19, 20) Kotlin: Operator call corresponds to a dot-qualified call 'age.compareTo(21)' which is not allowed on a nullable receiver 'age'.



经过一番修补后,我实现了所需的功能,如下所示:
class AlternativeCustomerTwo(
val name: String = "Name Not Provided",
var age: Int? = null,
var address: String = "Address not provided"
) {

var isApproved: Boolean = false
set(value) {
age?.let {
if(it >= 21) {
field = value
}
}
}
}

如果我这样称呼它:
val customer = AlternativeCustomerTwo(name = "John", age = 120)
customer.isApproved = true

然后打印:true

交替
val customer = AlternativeCustomerTwo(name = "John", age = 12)
customer.isApproved = true

它打印错误
我的问题是,这是正确的方法,还是我正在做一些可怕的Kotlin?

最佳答案

您正在使用kotlin的两种非常好的语言功能。
首先是let函数。它是一个作用域函数,它接受其调用对象(在您的情况下为 age )并将其提供为lambda的参数(在您的情况下为)。

第二个是安全 call (?。)功能。仅当调用对象为非null时,安全调用才会继续。

因此,只有在age不为null时,才会调用您的setter。

该技术由Kotlin语言设计师推荐。以下摘录摘自《运行中的 Kotlin 》一书,第6章,第144页

you can use the let function, and call it via a safe call. All the let function does is turn the object on which it’s called into a parameter of the lambda. If you combine it with the safe call syntax, it effectively converts an object of a nullable type on which you call let into a non-null type

关于kotlin - 检查空变量,然后在其上执行if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59377205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com