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.
Kotlin Initiative! Be another contributor by asking a question on SOPT
– Wallace Maxters