Re: Odd behaviour of List to Map coercion within function arguments

Simon Sadedin <[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <CAKOHk8PDFW4MsFXA1x8kmjocQsnMAtKBe1FKRSnPO5Qz7Lt5hw@mail.gmail.com>
On Mon, 18 Mar 2024 at 09:25, Paul King <[email protected]> wrote:

I am not sure I have the full history of when support started (at
> least 15+ years ago) but dynamic Groovy unwraps a list as arguments:
>
> def avg(int a, int b, int c) { (a + b + c)/3 }
> assert avg(1, 2, 3) == 2    // normal invocation
> def nums = [10, 20, 30]
> assert avg(nums) == 20    // args are a list
>
> It will only do this if the argument is a single List and no method
> matching a single List argument was found. Relevant implementation:
>
>
> https://github.com/apache/groovy/blob/master/src/main/java/groovy/lang/MetaClassImpl.java#L1242
>
> https://github.com/apache/groovy/blob/master/src/main/java/groovy/lang/MetaClassImpl.java#L1246-L1253
>
> You can turn this feature off with @TypeChecked/@CompileStatic.
>

 Thanks - that explains it perfectly!

Though it is still a bit disconcerting how it manifests as a type error at
run time that is data dependent that way. But at least knowing how it works
allows me to think about what's happening and how to handle it.

Cheers / thanks!,

Simon
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.