Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 36
Print an Object with toString()
ОглавлениеThis is definitely getting a little better. But the output is still empty, and the class is still basically useless. However, Kotlin gives you some things for free: most notably for now, every class automatically gets a toString()
method. You can run this method by creating an instance of the class (which you've already done) and then calling that method, like this:
val brian = Person("Brian", "Truesby") println(brian.toString())
Make this change to your main
function. Create a new Person
(give it any name you want), and then print the object instance using println
and passing into println
the result of toString()
.
NOTE You may be wondering where in the world that toString()
method came from. (If not, that's OK, too.) It does seem to sort of magically appear. But it's not magical it all. It's actually inherited. Inheritance is closely related to objects, and something we'll talk about in a lot more detail in both Chapter 3 and Chapter 5.