为什么一个泛型类型的属性可以为空?
我正在尝试创建一个泛型类型的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?
,我很困惑,为什么这是事实。
“默认的上限(如果没有指定)是Any?
”( http://kotlinlang.org/docs/reference/generics.html#generic-constraints )
换句话说,当你使用T
,Kotlin认为这可能是任何类型,无论是原始的,对象还是可空的引用。
TL; DR;
修复添加上面的类型:
class Test<T: Any> { ... }