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

Define a Custom Method on Your Class

Оглавление

What we need, then, is a new class method. Let's call it updateName(), and have it update the fullName property. Then, we can call updateName() every time a name needs to be changed. There's really nothing magical here, as you already have created a method with fun. Here's what you really want:

fun updateName() { fullName = "$firstName $lastName" }

This is actually the exact same code that already exists in your Person 's init block. But that code isn't needed anymore! Instead, you can call updateName() within your init block. Listing 2.8 shows you what Person should look like when you're finished.

Programming Kotlin Applications

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