Override toString method for a single object

Viewed 140

Suppose I have this code:

MyClass obj1 = new MyClass()
MyClass obj2 = new MyClass()

The toString() method in MyClass.groovy is implemented like this:

String toString() {
    "Instance of MyClass"
}

However, I would like obj1 to return something else when printed. How would I do that? I tried these two options, but neither worked.

obj1.metaClass.toString = {
    "Object 1"
}

and

obj1.toString = {
    "Object 1"
}

The first simply didn't work and the second caused an error. What is the correct way to do this in Groovy?

1 Answers

The correct syntax is this:

obj1.metaClass.toString = { ->
    "Object 1"
}

By not including -> the closure took a default parameter, but since the actual toString() method does not take any parameters, I was overriding the wrong method.

Edit: This only works if you manually include the call to toString() as in: print obj1.toString().

Related