recsater
recsater

Reputation: 11

How to initialize lateinit var with 'by keyword' in kotlin

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.

Upvotes: -1

Views: 169

Answers (1)

user8681
user8681

Reputation:

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
}

Upvotes: 2

Related Questions