[ 
https://issues.apache.org/jira/browse/GROOVY-10721?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17578313#comment-17578313
 ] 

Paul King commented on GROOVY-10721:
------------------------------------

It looks like Groovy has had that behavior for a long time:
[https://github.com/apache/groovy/commit/fdaa310a99]

And it has been finessed over time to account for enums:
[https://github.com/apache/groovy/commit/609d125ae]

So fields and init blocks are grouped and each group retains declaration order. 
This presumably met with certain expectations at the time for previously not 
working code.

Perhaps declaration order should be re-looked at. Given the breaking nature, it 
would be a Groovy 5 thing.

 

> Unexpected static initialization order
> --------------------------------------
>
>                 Key: GROOVY-10721
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10721
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 3.0.8, 4.0.4
>         Environment: openjdk 11.0.12 2021-07-20
>            Reporter: Luk N
>            Priority: Minor
>
> Hi, I've encountered a small issue - assignments to static fields and 
> executions of static blocks do not happen in the same order they do in Java. 
> I'm not sure if they should, hence the ticket. In Java the assignments and 
> executions are in the declaration order, while Groovy seems to initialize 
> fields first. Attached sample java class, executable in groovy too. 
> {noformat}
> import java.util.*;
> class ListSupplier{
>     public static List getList(){
>         System.out.println("Getting list");
>         return new ArrayList<>();
>     }
> }
> class ListThenStatic{
>     static final List list = ListSupplier.getList();
>     static{
>         System.out.println("Static block");
>     }
> }
> class StaticThenList{
>     static{
>         System.out.println("Static block");
>     }
>     static final List list = ListSupplier.getList();
> }
> class Test {
>     public static void main(String[] args) {
>         ListThenStatic listThenStatic = new ListThenStatic();
>         StaticThenList staticThenList = new StaticThenList();
>     }
> }{noformat}
> Java produces output:
>  # Getting list
>  # Static block
>  # Static block
>  # Getting list
> From Groovy:
>  # Getting list
>  # Static block
>  # Getting list
>  # Static block
> Is this behaviour expected and/or documented anywhere?



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to