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

Assign Your Property the Return Value from a Function

Оглавление

It's worth taking a minute to remember what the actual problem here is. You need to ensure that Kotlin sees an assignment of a value to fullName in one of three legal places:

 In the class's primary constructor

 In the property's declaration

 In the class's init block

You've also seen that simply calling another function—like updateName()—and letting that function do the assignment won't cut it.

The first thing we need to do is change our function. Why? Because it currently doesn't return a value—and that means that you can't use the function as the right side of an assignment. In other words, you can't get the all-important:

var fullName: String = // something here... like a function!

So change updateName() to actually return a value. While you're at it, let's also change the name to better reflect what it does now:

fun combinedNames(): String { return "$firstName $lastName" }

Now, you need a little cleanup:

1 Remove the reference to updateName() from init.

2 Assign fullName the return value from this function.

3 While you're at it, remove the init block entirely.

4 Move the declaration of the fullName property from the first line in Person to after all the other properties are declared.

WARNING Don't miss that last item! Now that you're using the values of firstName and lastName to initialize fullName, the order of property declaration matters. You need firstName and lastName to get assigned the values from the primary constructor before fullName is declared and combinedNames() is run.

You can see this all together in Listing 2.9.

Programming Kotlin Applications

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