How can I "delay" the initialization of a property?

8

There are situations when initializing the property can not be made in the declaration, its value is only known later.

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

Is there any way to "defer" initialization without declaring the property as nullable?

    
asked by anonymous 08.08.2017 / 16:24

1 answer

7

Probably the simplest way would be:

public lateinit var prop: String

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

Kotlin has properties much like the properties of C #, with a syntax better then it might look like there is a field, but it's a property, even if it does not have lateinit .

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

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

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

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 lateinit a 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.

    
08.08.2017 / 16:35