Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 77
LISTING 2.7: Defining custom mutators for lastName and firstName
Оглавлениеpackage org.wiley.kotlin.person class Person(_firstName: String, _lastName: String, _height: Double, _age: Int, _hasPartner: Boolean) { var fullName: String var firstName: String = _firstName set(value) { field = value } var lastName: String = _lastName set(value) { field = value } var height: Double = _height var age: Int = _age var hasPartner: Boolean = _hasPartner // Set the full name when creating an instance init { fullName = "$firstName $lastName" } override fun toString(): String { return fullName } }
WARNING The good news about Listing 2.7 is that you can literally copy the mutator code from firstName
to use again for lastName
. Since field
applies to whatever backing field is being used, it works for both properties. The bad news is that skimming Kotlin code can sometimes be hairy, because you'll see lots of blocks that look similar—just like these.