gpt4 book ai didi

android - 为什么我不能在 Kotlin 中为 int var 设置 Lateinit ?

转载 作者:行者123 更新时间:2023-12-02 17:13:15 28 4
gpt4 key购买 nike

我希望稍后初始化私有(private)a var id,所以我使用代码private lateinit var id:Int

但是我收到错误原始类型的属性不允许使用“lateinit”修饰符,为什么?我该如何修复它?谢谢!

代码A

class UIAddEditBackup: AppCompatActivity() {
private lateinit var mContext: Context //OK
private var isAdd: Boolean=false //OK
private lateinit var id:Int // I get the error

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_add_edit_backup)
id=5
}
}

最佳答案

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

对于 primite 类型,您只需删除 lateinit 修饰符并使用零(或 bool 值 false)进行初始化

关于android - 为什么我不能在 Kotlin 中为 int var 设置 Lateinit ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594089/

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