TL ; DR:
Override toString to return a string. Then println shows that string for the object.
class Cat(val name: String) {
override fun toString(): String {
return "Cat named $name"
}
}
// println(Cat("Tom")) prints Cat named Tom
Full lesson:
Every Kotlin class inherits a toString function from Any. Kotlin calls it to turn an object into text. The inherited one only knows the class name and a hash code:
Cat@1b6d3586
That tells you nothing about the cat.
So override toString, as you overrode functions before. Return the text that stands for the object.
Kotlin calls it whenever the object becomes text. println(tom) does that. So does a string template like "I have $tom".
toString takes no parameters and returns a String. It must return the text, not print it.
Your task
The Dog class below has a name and an age. Override toString in it.
It returns the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.
Expected output:
Rex is 3 years old
Bella is 5 years oldFree plan: 30 tutor messages. Premium is unlimited.
