Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 63

You Must Initialize Your Properties

Оглавление

Kotlin requires that you initialize your properties. If you try to compile the Person class in Listing 2.2, you're going to get an error like this:

Error:(6, 5) Kotlin: Property must be initialized or be abstract

Let's leave the abstract piece of that for later. The easiest fix is to update the Person constructor to require all of this information. That's pretty straightforward:

class Person(var firstName: String, var lastName: String, var height: Float, var age: Int, var hasPartner: Boolean) { var fullName: String // Set the full name when creating an instance init { fullName = "$firstName $lastName" } // other methods follow }

Now you have to pass in these properties, so they'll pass compilation. Also note that by putting them in the constructor, you don't have to declare them within the class body.

NOTE You can also create additional versions of a Person constructor if you want to only take in parts of this information on instance creation. We'll come back to that topic in more detail in Chapter 4.

Alternatively, you could assign these properties values in the init method, as you did with fullName. However, there's no real way to come up with values for height, age, or whether the person has a partner without taking in input, so this is the more sensible approach.

Now you're ready to go back to main and do some type-related work.

Programming Kotlin Applications

Подняться наверх