简体   繁体   English

Kotlin中的原始类型属性不允许使用lateinit修饰符

[英]lateinit modifier is not allowed on primitive type properties in Kotlin

I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity . 我在kotlin定义了一个实例变量,并希望在activity onCreate方法上初始化它。

var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Here I am getting a below error on count variable. 这里我在计数变量上得到一个以下错误。

Property must be initialized or be abstract in Kotlin 属性必须在Kotlin中初始化或抽象

Well, I read this thread Property must be initialized or be abstract and tried same but again I am getting a below error. 好吧,我读过这个帖子属性必须初始化或者是抽象的并且尝试相同但是我再次得到以下错误。

lateinit modifier is not allowed on primitive type properties 原始类型属性不允许使用lateinit修饰符

lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Is there any way to do this in Kotlin ? Kotlin有什么办法吗?

There are several ways to resolve this issue. 有几种方法可以解决此问题。

You can Initialise it with default value (ei 0 or -1 or whatever) and then initialise it whenever your logic says. 您可以使用默认值(ei 0-1或其他)初始化它,然后在逻辑说明时初始化它。

Or tell compiler that count will be initialised later in this code by using Delegates.notNull check notNull . 或者通过使用Delegates.notNull检查notNull告诉编译器将在此代码中稍后初始化count

var count: Int by Delegates.notNull<Int>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // You can not call `Int.inc()` in onCreate()` function until `count` is initialised.
    // count.inc()
    // **initialise count** 
}

And if you need count value on demand (if not necessary to initialise in onCreate ), you can use lazy function. 如果你需要按需计数值(如果没有必要在onCreate初始化),你可以使用lazy函数。 Use this only if you have an intensive (Some calculation/Inflating a layout etc) task that you want to do on demand , Not to just assign a value. 仅当您要on demand执行密集(某些计算/充气布局等)任务时才使用此选项,而不仅仅是分配值。

var count:Int by lazy {
    // initialise
}

Now you can decide what to use. 现在您可以决定使用什么。

I hope it helps. 我希望它有所帮助。

There's no reason to leave it uninitialized. 没有理由让它没有初始化。 Just initialize it to 0 or -1. 只需将其初始化为0或-1即可。

lateinit is for non-null object references that can't easily be initialized in the class body definition. lateinit用于非null对象引用,无法在类体定义中轻松初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM