« Return to Thread: can't override toString in coerced Map... some of the time

Re: can't override toString in coerced Map... some of the time

by Andres Almiray :: Rate this Message:

Reply to Author | View in Thread

Seems like this issue is related to coercing any interface as the following code shows

interface Foo {
   String foo()
}
class Bar {
   String bar() { "Bar!" }
   String toString() { "From Bar" }
}

def concreteFoo = [
   foo: { "Foo!" },
   toString: { "from Proxy" }
] as Foo
def concreteBar = [
   bar: { "Baz!" },
   toString: { "from Proxy" }
] as Bar

println concreteFoo
println concreteBar

------ OUTPUT -------

["foo":Script33$_run_closure1@19d9740, "toString":Script33$_run_closure2@135128f]
from Proxy

The same would happen to the usual suspects (equals, hashCode). I'm not sure if this is a design constraint.


Maurice Nicholson-2 wrote:
Hey all,

I *love* the fact the Maps can be coerced into arbitrary types. It's what I
use all the time in Groovy unit tests.

But what's up with this? I can't seem to override or invoke the toString in
a Map coerced to org.compass.core.CompassQuery, but a URL proxy Map works
fine:

--- console ---

import org.compass.core.CompassQuery

def query = [toString: {-> 'this is the query'}] as CompassQuery

println query.toString()
println query.'toString'()

def socket = [toString: {-> 'this is the socket'}] as Socket

println socket.toString()

--- output ----

groovy> import org.compass.core.CompassQuery
groovy> def query = [toString: {-> 'this is the query'}] as CompassQuery
groovy> println query.toString()
groovy> println query.'toString'()
groovy> def socket = [toString: {-> 'this is the socket'}] as Socket
groovy> println socket.toString()

["toString":Script3$_run_closure1@bccf21]
["toString":Script3$_run_closure1@bccf21]
this is the socket

--- snip ---

Any ideas?

Thanks,
Maurice

 « Return to Thread: can't override toString in coerced Map... some of the time