Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 38
Print an Object (and Do It with Shorthand)
ОглавлениеYou can run the println
function at any time, and you just pass it something to print. So you could say:
println("How are you?")
and you'd just get that output in your results window. You can also have it print the result from a method, like toString()
, which is what you did earlier. But there's another shortcut. If you pass in something to println()
that has a toString()
method, that method is automatically run. So you can actually trim this code:
println(brian.toString())
down to just this:
println(brian)
In the latter case, Kotlin sees an object passed to println()
and automatically runs brian.toString()
and passes the result on for printing. In either case, you'll get output that looks something like this:
Person@7c30a502
That's not very useful, is it? It's essentially an identifier for your specific instance of Person
that is useful to Kotlin internals and the JVM, but not much else. Let's fix that.