-1

I want to initialize lateinit variable with 'by'.

How can I?

lateinit var test: int

fun main() {
    test by something {} // error!
}

I tried using by in by lazy, and I tried using by in lateinit var, but it didn't work.

recsater
  • 1
  • 2

1 Answers1

2

You don't need lateinit when using by lazy. Lazy means it'll be initialized the first time it's referenced. lateinit means you manually assign a value some time after construction.

So all you need is

val test by lazy { something() }

fun main() {
    println(test) // runs the initializer and prints the value
}

Update: Or, if you want to initialize an exising lateinit property:

lateinit var test: Type
fun main() {
  val someting by other
  test = something
}
Jorn
  • 20,612
  • 18
  • 79
  • 126
  • No, I don't mean that I want to use the by-lazy keyword and lateinit together, but I want to initialize the variable declared as lateinit through the by keyword. – recsater Feb 13 '23 at 05:24
  • @recsater See updated answer. Does that cover it? I don't think it's possible to do it without the intermediate variable. – Jorn Feb 13 '23 at 08:17