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

Initialize a Class with a Block

Оглавление

In most programming languages, Java included, a constructor takes in values (as it does in your Person class) and perhaps does some basic logic. Kotlin does this a bit differently; it introduces the idea of an initializer block. It's this block—identified conveniently with the init keyword—where you put code that should run every time an object is created.

This is a bit different than you may be used to: data comes in through a constructor, but it's separated from the initialization code, which is in the initializer block.

In this case, the initializer block uses the new fullName variable and sets it using the first and last name properties passed in through the class constructor:

// Set the full name when creating an instance init { fullName = "$firstName $lastName" } Then this new variable is used in toString(): override fun toString(): String { return fullName }

WARNING As much new material as this chapter introduces, you may have just run across the most important thing that you may learn, in the long-term sense. By changing toString() to use fullName, rather than also using the firstName and lastName variables directly, you are implementing a principle called DRY: Don't Repeat Yourself.

In this case, you're not repeating the combination of first name and last name, which was done already in the initializer block. You assign that combination to a variable, and then forever more, you should use that variable instead of what it actually references. More on this later, but take note here: this is a big deal!

Programming Kotlin Applications

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