gpt4 book ai didi

kotlin - 为什么泛型类型属性可以为空?

转载 作者:IT老高 更新时间:2023-10-28 13:26:59 24 4
gpt4 key购买 nike

我正在尝试使用泛型类型的 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/

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