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

Override Mutators for Certain Properties

Оглавление

You're now finally ready to do what we set out to do: override how changing a first name or last name works. First, you need to see how a typical mutator is defined.

Here's some more rather Kotlin-specific code that defines a custom mutator; in this case, it's for firstName :

var firstName: String = _firstName set(value) { field = value }

The set keyword tells Kotlin that this is a mutator. Additionally, Kotlin assumes that the mutator is for whatever property was just defined.

WARNING Kotlin uses a property's definition line in a file to determine that, if there's a custom mutator (or accessor), that definition is on the very next line. That's a big deal, and worth noting.

Then, value represents the value coming into the mutator. So in the following example, value would come to the firstName mutator as “Bobby”:

// Change Brian's first name brian.firstName = "Bobby"

Now here's where things look a little odd. There's this line:

field = value

What's going on there? What the heck is field ? Well, it's the property being mutated. It's what's called a backing field. So here, field references the backing field for the property, which is firstName (because that's the property just defined). That backing field is assigned the value passed into the mutator—in our example, that's the String “Bobby.”

The final piece here is understanding why you can't say something like this:

var firstName: String = _firstName set(value) { firstName = value }

This will actually compile, but it will give you a horrible error when you try to run and use this class. The problem is that when Kotlin sees this:

firstName = value

it interprets that as “run the code that mutates firstName.” But that code is the code already running. So it calls itself—a concept called recursion—and that same line runs again. And again. And again. And… well, you get the idea.

By using the backing field field, you avoid this recursion, and things behave. Go ahead and create a custom mutator for firstName and lastName ; things should look like Listing 2.7 when you're finished.

Programming Kotlin Applications

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