Extension field eager init

Extension fields are available only using backing fields which implies lazy initialization. Is there a way to eagerly init extension filed?

I think I’m probably a bit confused about what you’re asking, but I think that this is what you’re looking for:

class Test
val myFieldValue = run {
    println("field got initalised")
    42
}
val Test.myValue: Int get() = myFieldValue

fun main() {
    println(Test().myValue)
    val myTest = Test()
    println(myTest.myValue)
    for(i in 1..10)
        println(myTest.myValue.toString() + " Iteration: " + i)
}

I will give more context: I need to write an extension function for the Android fragment. The function should call registerForActivityResult(). Something like this

val AuthFragment.listener: ActivityResultLauncher<> 
    get() = registerForActivityResult(...) {
    }

fun AuthFragment.launchAuth() {
    asyncFunc {
        listener.launch()
    }
}

The problem is registerForActivityResult should be called before onCreate(). But since I have asyncFunc it is not guaranteed it will be called earlier than onCreate()

1 Like