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

Terminology Update: Getters, Setters, Mutators, Accessors

Оглавление

A getter is a method that allows you to get a value. For instance, you can add this into your main function, and it will not only work, but print out just the first name of the brian Person instance:

// Create a new person val brian = Person("Brian", "Truesby") println(brian.firstName)

This works because you have a getter on Person for firstName. You can do the same with fullName and lastName, too. This getter is, more formally, an accessor. It provides access to a value, in this case a property of Person. And it's “free” because Kotlin creates this accessor for you.

Kotlin also gives you a setter, or (again, more formally) a mutator. A mutator lets you mutate a value, which just means to change it. So you can add this into your program:

// Create a new person val brian = Person("Brian", "Truesby") println(brian.firstName) // Create another person val rose = Person("Rose", "Bushnell") rose.lastName = "Bushnell-Truesby"

Just as you can get data through an accessor, you can update data through mutators.

WARNING For the most part, I'll be calling getters accessors, and calling setters mutators. That's not as common as “getter” or “setter,” but as a good friend and editor of mine once told me, a setter is a hairy and somewhat fluffy dog; a mutator lets you update class data. The difference—and his colorful explanation—has stuck with me for 20 years.

Now, if you've gone ahead and compiled this code, you've run into yet another odd error, and that's the last thing to fix before moving on from this initial foray into objects.

Programming Kotlin Applications

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