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

All Data Is Not a Property Value

Оглавление

You have a constructor and it takes in two pieces of data: firstName and lastName. That's controlled by the constructor declaration:

class Person(firstName: String, lastName: String) {

But here's what is tricky: just accepting those values does not actually turn them into property values. That's why you get the error in Figure 1.10; your Person object accepted a first and last name, but then promptly ignored them. They aren't available to be used in your toString() overridden method.

You need to use the val keyword in front of each piece of data to turn that data into property values. Here's the change you need to make:

class Person(val firstName: String, val lastName: String) {

Specifically, by using val (or var, which we'll talk about shortly), you've created variables, and assigned them to the Person instance being created. That then allows those variables (or properties, to be even more precise) to be accessed, like in your toString() method.

Make these changes (see Listing 1.5 to make sure you're caught up) and then compile and run your program.

Programming Kotlin Applications

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