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

Override the toString() Method

Оглавление

One of the cool things about a class method is that you can write code and define what that method does. We haven't done that yet, but it's coming soon. In the meantime, though, what we have here is slightly different: a method that we didn't write code for, and that doesn't do what we want.

In this case, you can do something called overriding a method. This just means replacing the code of the method with your own code. That's exactly what we want to do here.

First, you need to tell Kotlin that you're overriding a method by using the override keyword. Then you use another keyword, fun, and then the name of the method to override, like this:

override fun toString()

NOTE Earlier, you learned the difference between a function and a method. And toString() is definitely a method, in this case on Person. So why are you using the fun keyword? That looks an awful lot like “function,” and that's, in fact, what it stands for.

The official answer is that Kotlin essentially sees a method as a function attached to an object. And it was easier to not use a different keyword for a standalone function and an actual method.

But, if that bugs you, you're in good company. It bugs me, too! Still, for the purposes of Kotlin, you define both functions and methods with fun.

But toString() adds a new wrinkle: it returns a value. It returns a String to print. And you need to tell Kotlin that this method returns something. You do that with a colon after the parentheses and then the return type, which in this case is a String :

override fun toString(): String

Now you can write code for the method, between curly braces, like this:

class Person(firstName: String, lastName: String) { override fun toString(): String { return "$firstName $lastName" } }

This looks good, and you've probably already figured out that putting a dollar sign ( $) before a variable name lets you access that variable. So this takes the firstName and lastName variables passed into the Person constructor and prints them, right?

Well, not exactly. If you run this code, you'll actually get the errors shown in Figure 1.10.


FIGURE 1.10 Why doesn't this override of toString() work?

What gives here? Well, it turns out to be a little tricky.

Programming Kotlin Applications

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