Kotlin 中的原始类型属性不允许使用 lateinit 修饰符 [英] lateinit modifier is not allowed on primitive type properties in Kotlin

查看:37
本文介绍了Kotlin 中的原始类型属性不允许使用 lateinit 修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 kotlin 中定义了一个实例变量,并希望通过 activityonCreate 方法对其进行初始化.

I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

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.

属性必须在 Kotlin 中初始化或抽象

Property must be initialized or be abstract in 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修饰符

lateinit modifier is not allowed on primitive type properties

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

有没有办法在 Kotlin 中做到这一点?

Is there any way to do this in Kotlin ?

推荐答案

有多种方法可以解决此问题.

There are several ways to resolve this issue.

您可以使用默认值(e.i 0-1 或其他)初始化它,然后在您的逻辑说到时初始化它.

You can Initialise it with default value (e.i 0 or -1 or whatever) and then initialise it whenever your logic says.

或者通过使用 Delegates.notNull 检查 notNull.

Or tell compiler that count will be initialised later in this code by using Delegates.notNull check notNull.

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** 
}

如果你需要按需计数值(如果不需要在onCreate中初始化),你可以使用lazy函数.仅当您要按需执行密集(一些计算/扩展布局等)任务时才使用此功能,而不仅仅是分配一个值.

And if you need count value on demand (if not necessary to initialise in onCreate), you can use lazy function. 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.

var count:Int by lazy {
    // initialise
}

现在您可以决定使用什么.

Now you can decide what to use.

希望能帮到你.

这篇关于Kotlin 中的原始类型属性不允许使用 lateinit 修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆