July 2018
Intermediate to advanced
400 pages
12h 14m
English
You saw earlier in the chapter that order is important when using initializer blocks – you must ensure that all properties used in the block are initialized before the initializer block is defined. Take a look at the following code that shows this initializer block ordering problem:
class Player() {
init {
val healthBonus = health.times(3)
}
val health = 100
}
fun main(args: Array<String>) {
Player()
}
This code would not compile, because the health property is not initialized at the point that it is used by the init block.
As we mentioned earlier, when a property is used within an init block, the property initialization must happen before it is accessed.
When health is defined before ...
Read now
Unlock full access