Using toString() automatically?

In C#/Java, we have toString() that returns the string representation of an
object. When you use Console.writeLine() or System.out.println(), and pass an object,
it will use toString() automatically.

When I write my own toString() function, I have to use it manually:

class Character {

    construct new(name,life){
        _name = name
        _life = life
    }

    toString(){
        return "Name: %(_name) Life: %(_life)"
    }

var nova = Character.new("Nova",100)
System.print(nova.toString())

How do I get print() to use it automatically?

>Solution :

Use a getter instead of a function:

toString { "Name: %(_name) Life: %(_life)"}

var nova = Character.new("Nova",100)
System.print(nova) # Output: Name: Nova Life: 100

Leave a Reply