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

查看:331
本文介绍了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()
}

在这里,我得到了关于count变量的以下错误.

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.

您可以使用默认值(例如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告诉编译器该计数稍后将在此代码中初始化

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函数.仅当您要执行密集的(某些计算/布局的膨胀等)任务时,才使用此功能on demand,而不仅仅是分配值.

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天全站免登陆