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

LISTING 1.6: Creating a new property for a Person

Оглавление

class Person(val firstName: String, val lastName: String) { val fullName: String // Set the full name when creating an instance init { fullName = "$firstName $lastName" } override fun toString(): String { return fullName } } fun main() { // Create a new person val brian = Person("Brian", "Truesby") // Create another person val rose = Person("Rose", "Bushnell") println(brian) }

You'll see a number of new things here, but none are too surprising. First, a new variable is declared inside the Person object: fullName. This is something you've already done in your main function. This time, though, because you're doing it inside the Person object, it automatically becomes part of each Person instance.

Another small change is the addition of a new Person instance in main ; this time it's a variable named rose.

Then, there's a new keyword: init. That bears further discussion.

Programming Kotlin Applications

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