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

LISTING 1.7 Using mutable variables

Оглавление

class Person(var firstName: String, var lastName: String) { var 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") println(brian) // Create another person val rose = Person("Rose", "Bushnell") println(rose) // Change Rose's last name rose.lastName = "Bushnell-Truesby" println(rose) }

Here, fullName has been made mutable, and there's a little more printing in main. It should compile and run without error now.

But wait! Did you see your output? There's a problem! Here's what you probably get when you run your code:

Brian Truesby Rose Bushnell Rose Bushnell

Despite what Meat Loaf had to say about two out of three not being bad, this is not great. Why is Rose's name in the last instance not printing with her new last name?

Well, to solve that, it's going to take another chapter, and looking a lot more closely at how Kotlin handles data, types, and more of that automatically running code.

Programming Kotlin Applications

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