Initializer Blocks
In addition to the primary and secondary constructors, you can also specify an initializer block for a class in Kotlin. The initializer block is a way to set up variables or values as well as perform validation – like checking to make sure that the arguments to the constructor are valid ones. The code it holds is executed when the class is constructed.
For example, players have certain requirements as they are constructed: A player must begin the game with at least one health point. Their name must not be blank.
Use an initializer block, denoted by the init keyword, to enforce these requirements with preconditions.
Listing 13.8 Defining an initializer block (Player.kt)
class Player(_name: String, var healthPoints: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access