October 2021
Intermediate to advanced
500 pages
16h 23m
English
An extension can also be defined for use with a nullable type. Defining an extension on a nullable type allows you to deal with the possibility of the value being null within the body of the extension function, rather than at the call site.
Add an extension for nullable Rooms in Extensions.kt that will return a room outside the town of Kronstadt.
Listing 19.15 Adding an extension on a nullable type (Extensions.kt)
...
infix fun Coordinate.move(direction: Direction) =
direction.updateCoordinate(this)
fun Room?.orEmptyRoom(name: String = "the middle of nowhere"): Room =
this ?: Room(name)
Use your extension function in the move function, letting the player walk outside the bounds of town.
Read now
Unlock full access