Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 71
Move Properties Out of Your Primary Constructors
ОглавлениеYou've actually just stumbled onto a fairly standard best practice in Kotlin: it's often a good idea to move property definitions out of the primary constructor. You'll recall that you started like this way back in Chapter 1:
class Person(firstName: String, lastName: String) {
Then, before you added other properties, you added the var
keyword to each listed data input:
class Person(var firstName: String, var lastName: String) {
This made firstName
and lastName
properties, with automatically generated accessors and mutators. The problem is that, while expedient at the time, this has now come back to bite you.
To undo this, simply remove var
from all of the properties in the current version of the Person
constructor:
class Person(firstName: String, lastName: String, height: Double, age: Int, hasPartner: Boolean) {
Now try to run your PersonApp
, and you're going to see an error discussed earlier:
Error:(13, 10) Kotlin: Unresolved reference: lastName
You should recall that because lastName
is not a property anymore (because there's no var
or val
keyword in the constructor definition), Kotlin does not create accessors or mutators. That means that this line in main
now won't work:
rose.lastName = "Bushnell-Truesby"
So there's a bit of an apparent conflict that has arisen:
You can't customize accessors or mutators if a property is declared in a class's constructor.
If a property isn't declared in a class's constructor, and it's not declared elsewhere in the class, you don't get an automatic accessor or mutator.