Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 73
LISTING 2.5: Assigning constructor information to properties
Оглавлениеpackage org.wiley.kotlin.person class Person(firstName: String, lastName: String, height: Double, age: Int, hasPartner: Boolean) { var fullName: String var firstName: String = firstName var lastName: String = lastName 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 } }
Take just the line dealing with firstName
:
var firstName: String = firstName
A property is declared, and it's both read and write, because var
is used. (Remember, if you wanted this to be a read-only property, you'd use val
.) That property is given a name— firstName
—and then a type, String
. Then, the new property is assigned a value. In this case, that value is whatever is passed into the constructor through firstName
.
You can now compile your code and run it, and it works again! (Although there's still that last name issue to fix. But you're getting closer.)