Constructors
Player now contains behavior and data you defined. For example, you specified a name property:
var name = "madrigal" get() = field.replaceFirstChar { it.uppercaseChar() } private set(value) { field = value.trim() }
With this current implementation, every player begins as “madrigal” and needs to change their name after the fact, which might involve roping in various bureaucracies in NyetHack. It would be better to create the Player instance with the correct name.
This is where a primary constructor comes into play. A constructor allows its caller to specify the initial values that an instance of a class requires in order to be constructed. Those values are then available for assignment to the properties defined ...
Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.