How can I "postpone" the startup of a property?

Asked

Viewed 420 times

9

There are situations where the property initialization is not possible to be made in the declaration, its value is only known later.

An example of this is, on Android, references to views of a layout can only be obtained after the use of the method setContentView().

Is there any way to "postpone" initialization without the need to declare the property as nullable?

  • 3

    Kotlin Initiative! Be another contributor by asking a question on SOPT

1 answer

7


Probably the simplest way would be:

public lateinit var prop: String

fun init(param: String) {
   valor = Executa(param)
}

Kotlin has estates much like the properties of C#, with a better syntax, so it may seem that there is a field, but it is a property, even if it did not have the lateinit.

Things like setContentView() are an impedance of Kotlin with Java because it uses the simulated way of property of Java. There’s even a way to solve this even if it’s not simple. I think it would be worth the effort in the name of style standardization in the language, would do as Typescript solved impedance with Javascript.

There are several other ways. See about lazy and delegated properties.

val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

I put in the Github for future reference.

This way only when it is needed will it be initialized. In general this is used for something that may never be necessary for the object and to generate its value may have a heavy processing or that may have an altered value during the process between the creation of the object and its first use.

This way you can use with val since initialization occurs late. Without the lateinit one val needs a value since it can no longer have its value changed. It stays in an invalid state until needed, which is different from having a null value and then having another value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.