Anton,

> ...You cannot refer to the method of an object that has not yet been 
> constructed.

As a matter of fact, you can. This darned Java “method-calling” lingo is 
terribly misleading; we definitely should have sticked with Alan Kay's 
“message-sending”, and there would be much less misunderstandings and problems 
today.

Anyway, Groovy (just like any other at least half-decent language) supports 
late-binding, which means you can essentially “call” anything of anything, and 
the dispatcher at the runtime would do its best to find the proper method and 
call it. Try e.g.,

class Foo {
   static foo0() { println "foo0"}
   static foo1() { println "foo1"}
}
Foo.metaClass.static."foo${1+1}"={ -> println "even this works OK!" }
3.times { Foo."foo$it"() }

The problem with the original code

>> def a = [boo : {
>>    foo()
>> }] as Boo

is — precisely as Mariusz presumed — that the closure's delegate/owner/this is 
the script object, not a. Alas, I can't see any elegant way to fix the problem; 
about the best I could think of is

def block={ foo() }
def a=[boo: block] as Boo
block.delegate=a

which should work as expected.

All the best,
OC


> On 14 Oct 2020, at 17:12, Anton Shepelev <anton....@gmail.com> wrote:
> 
> Mariusz W:
> 
>> class Boo {
>>    def boo() {throw new UnsupportedOperationException("should override")}
>>    def foo() { println "foo"}
>> }
>> 
>> def a = [boo : {
>>    foo()
>> }] as Boo
>> 
>> a.boo()
> 
> As far as I can see (which is not a great distance away from
> my nose), you are trying to construct an object with the
> boo() method redefined to call the foo() method of the
> parent class. I believe your code is incorrect at least
> becuause the foo() method is unavailable at the point of
> construction. You cannot refer to the method of an object
> that has not yet been constructed.
> 

Reply via email to