July 2018
Intermediate to advanced
400 pages
12h 14m
English
When a class property is both nullable and mutable, you must ensure that it is non-null before referencing it. For example, consider the following code that checks whether a player is wielding a weapon (since the player may have been disarmed or dropped their weapon) and, if so, prints its name:
class Weapon(val name: String)
class Player {
var weapon: Weapon? = Weapon("Ebony Kris")
fun printWeaponName() {
if (weapon != null) {
println(weapon.name)
}
}
}
fun main(args: Array<String>) {
Player().printWeaponName()
}
You may be surprised to learn that this code does not compile. Check out the error to see why (Figure 12.7):
Figure 12.7 Smart cast to ‘Weapon’ is impossible ...
Read now
Unlock full access