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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…