I am trying to create a subclass of HashMap
with its own string representation. I figured that I just needed to override toString()
in the subclass:
class Foo extends HashMap {
String toString() {
"foo"
}
}
This works, insofar as I can do (new Foo()).toString()
and it returns the string foo
. However, in a string interpolation context (or when using as String
), the toString
implementation of HashMap
seems to rule:
Foo test = new Foo()
test["abc"] = 123
println "${test.toString()}" // Prints: foo
println "${test}" // Prints: [abc:123]
println (test as String) // Prints: [abc:123]
I’m curious why this happens and what — if anything — I can do to get around it?