Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 83
Tell Kotlin You'll Initialize a Property Later
ОглавлениеAnother easy solution is to explicitly tell Kotlin that you are going to initialize a property later. It's sort of the equivalent of saying, “Look, Kotlin, trust me. I promise I'll take care of this.” To do this, you preface a property declaration with lateinit
, a keyword that means what it sounds like—you'll initialize the property in question later:
class Person(_firstName: String, _lastName: String, _height: Double, _age: Int, _hasPartner: Boolean) { lateinit var fullName: String
Remove the assignment to “”
and add lateinit
. Now, your class will compile again! No problem.
WARNING lateinit
has some pretty specific limitations. It only works with var
, not val
, and the properties can't be declared within the constructor itself. You also can't create a custom accessor or mutator for a lateinit
-declared property. So it's not a fix-all. In fact, it's not even a fix in this case, really.
While it might seem this solves your problem, that's not actually true. You still have the same problem as assigning an empty string to fullName
: you've built a silent dependence on updateName()
being called in init
. Kotlin is no longer checking for you, because you said, “I'll take care of it.”
So this is still a fragile solution, and in some cases, even more dangerous than just using a dummy value to start with.