作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用泛型类型的 lateinit
不可为空的属性创建参数化类:
class Test<T> {
private lateinit var t : T
private lateinit var s : String
}
后者是允许的,但前者是不允许的。编译器返回以下错误:
Error:(7, 11) ''lateinit'' modifier is not allowed on nullable properties
由于我没有声明 T?
,我很困惑为什么会这样。
最佳答案
The default upper bound (if none specified) is
Any?
(Source)
换句话说,当您使用 T
时,Kotlin 假定这可能是 任何 类型,无论是原始类型、对象还是可为空的引用。
要解决这个问题,请添加一个上部类型:
class Test<T: Any> { ... }
关于kotlin - 为什么泛型类型属性可以为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33021802/
我是一名优秀的程序员,十分优秀!