num
设置时应该可以为空,但它返回的内容应该始终不可为空(具有默认值)。
class Test {
var num: Int? = null
get() = field ?: 5 // default value if null
}
即使返回值始终为非空,以下内容也不会编译,这对我来说很有意义,因为类型不是推断出来的,而是从支持字段中获取的:
val a: Int = Test().num
Type mismatch: inferred type is Int? but Int was expected
问题是如何将该 getter 的返回类型更改为不可为空?如果我这样做,编译器会说:
Getter return type must be equal to the type of the property, i.e. 'Int?'
我知道我可以用另一个属性来解决它
numNotNullable
(没有支持字段)。class Test {
var num: Int? = null
get() = field ?: 5 // default value if null
val numNotNullable: Int
get() = num ?: 5
}
val c: Int = Test().numNotNullable
但这不是我想要的。 还有其他方法吗?
最佳答案
var num: Int? = null
这是您的属性(property)签名。没关系,如果你在内部确保没有 null
值被返回。签名说,该值可以为空。
这意味着:
null
到此字段 null
的事实。 您具有第二个属性的解决方案很好。
您当然可以用普通的旧 java bean 替换该属性,但我不建议这样做,因为您必须使用
getNumb
访问该属性。和 setNum
.class Test {
private var num: Int = 5
fun setNum(num: Int?) {
this.num = num ?: 5
}
fun getNum() = num
}
关于kotlin - 即使支持字段可以为空,getter 也会返回不可为空的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46606504/