You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Eric Milles (Jira)" <ji...@apache.org> on 2021/03/21 18:32:00 UTC

[jira] [Resolved] (GROOVY-9977) @CompileStatic does not work when a class field has a lambda initializer

     [ https://issues.apache.org/jira/browse/GROOVY-9977?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel ]

Eric Milles resolved GROOVY-9977.
---------------------------------
    Fix Version/s: 4.0.0-alpha-3
       Resolution: Fixed

> @CompileStatic does not work when a class field has a lambda initializer
> ------------------------------------------------------------------------
>
>                 Key: GROOVY-9977
>                 URL: https://issues.apache.org/jira/browse/GROOVY-9977
>             Project: Groovy
>          Issue Type: Bug
>          Components: Static compilation, Static Type Checker
>    Affects Versions: 3.0.7, 4.0.0-alpha-2
>         Environment: OpenJDK8
>            Reporter: Lyuben Atanasov
>            Assignee: Eric Milles
>            Priority: Major
>             Fix For: 4.0.0-alpha-3
>
>          Time Spent: 50m
>  Remaining Estimate: 0h
>
> Using {{@CompileStatic}} when a field is initialized with a lambda:
> {code}
> class LambdaAssignedToField
> {
> 	private Comparator<Integer> myComparator = (int1, int2) -> Integer.compare(int1, int2);
> }
> {code}
> causes compilation errors:
> {noformat}
> Exception in thread "main" org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
> Script_28800dd8352617dbb4fe2e1957614875.groovy: 3: [Static type checking] - Cannot find matching method java.lang.Integer#compare(java.lang.Object, java.lang.Object). Please check if the declared type is correct and if the method exists.
>  @ line 3, column 61.
>    yComparator = (int1, int2) -> Integer.co
>                                  ^
> Script_28800dd8352617dbb4fe2e1957614875.groovy: 3: [Static type checking] - Cannot assign value of type groovy.lang.Closure <java.lang.Object> to variable of type java.util.Comparator <Integer>
>  @ line 3, column 45.
>    rator<Integer> myComparator = (int1, int
> {noformat}
> The same code, used in the context of a method, works fine:
> {code}
> class LambdaAssignedToVariable
> {
> 	public void test()
> 	{
> 		Comparator<Integer> myComparator = (int1, int2) -> Integer.compare(int1, int2);
> 	}
> }
> {code}
> In order to make the first example compile, I have to manually specify the types of the lambda parameters and also cast it to the correct type:
> {code}
> class LambdaAssignedToFieldCast
> {
> 	private Comparator<Integer> myComparator = (Comparator<Integer>) (Integer int1, Integer int2) -> Integer.compare(int1, int2);
> }
> {code}
> The issue seems to exist since Groovy 3.0.0.



--
This message was sent by Atlassian Jira
(v8.3.4#803005)