Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 82
Assign an Uninitialized Property a Dummy Value
ОглавлениеThe easiest fix here is actually quite … easy. You can simply get around Kotlin's insistence on property initialization by assigning it an empty value at creation, such as an empty String
: “”
. Just add this to your class:
class Person(_firstName: String, _lastName: String, _height: Double, _age: Int, _hasPartner: Boolean) { var fullName: String = ''
Kotlin will now stop complaining! You've initialized fullName
, so there's not a problem. However, this is a bit hacky. It defeats the purpose of Kotlin's checking (something we'll come back to in a moment). It also builds a hidden dependency in your code. Look at the init
method again:
// Set the full name when creating an instance init { updateName() }
Even with the comment, there's nothing except your own memory and understanding of how Person
works—and this chapter—that tells you that you have to call updateName()
in init
. If you don't, then fullName
will not get initialized, and that, in turn, will mess up the toString()
function. Bad news!
If this seems unlikely, it's not. When you're writing code, you know what that code is supposed to do. But leave that code for a few weeks, or months, and you often forget how it worked, let alone why you wrote it that way! Worse, but just as likely, someone else comes back to it later and has no idea how it works.
In both cases, it would be quite plausible that someone well-meaning forgets that updateName()
must be called in init
, removes or moves it, and problems ensue. This is really a fragile solution.