Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 72
Initialize Properties Immediately
ОглавлениеNow, just to make this a bit more complicated, there's another rule you've run across, too:
Any property not defined in a constructor must be initialized on instance creation.
To remember how this shows up, go ahead and define all the properties declared in your constructor, but this time do it just under the constructor line, similar to how you defined lastName
:
class Person(firstName: String, lastName: String, height: Double, age: Int, hasPartner: Boolean) { var fullName: String var firstName: String var lastName: String var height: Double var age: Int var hasPartner: Boolean // Set the full name when creating an instance init { fullName = "$firstName $lastName" }
Compile, run, and you'll get another error you've seen before, but this time with all of your properties:
Error:(6, 5) Kotlin: Property must be initialized or be abstract Error:(7, 5) Kotlin: Property must be initialized or be abstract Error:(8, 5) Kotlin: Property must be initialized or be abstract Error:(9, 5) Kotlin: Property must be initialized or be abstract Error:(10, 5) Kotlin: Property must be initialized or be abstract
This cropped up with firstName
, and we fixed it by setting that value in your code's init
block. We need to do something somewhat similar here: we need to assign to each new property the value that is passed into the constructor. So the property firstName
should be given the value passed into firstName
that's declared as an input to the Person
constructor.
NOTE If that sentence seemed confusing, you're in good company. Two firstName
pieces of information are floating around here: the one passed into the constructor, and the property name. That's a problem we'll fix shortly.
Kotlin gives you a way to this assignment but it's going to look a little odd. Basically, the values that come into your constructor are available to your properties at creation time, and you can assign them directly to those properties. That's a little easier said than described, so take a look at the new version of Person
shown in Listing 2.5.