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

        return "Name: %(_name) Life: %(_life)"

var nova ="Nova",100)

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

>Solution :

Use a getter instead of a function:

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

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

Leave a Reply