lateinit modifier is not allowed on primitive type properties in Kotlin

前端 未结 2 1105
故里飘歌
故里飘歌 2020-12-03 09:47

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

var count:         


        
相关标签:
2条回答
  • 2020-12-03 10:19

    There are several ways to resolve this issue.

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

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

    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.

    I hope it helps.

    0 讨论(0)
  • 2020-12-03 10:20

    There's no reason to leave it uninitialized. Just initialize it to 0 or -1.

    lateinit is for non-null object references that can't easily be initialized in the class body definition.

    0 讨论(0)
提交回复
热议问题