codeconsole opened a new pull request, #3336:
URL: https://github.com/apache/groovy/pull/3336

   [GROOVY-12822](https://issues.apache.org/jira/browse/GROOVY-12822)
   
   Under `@CompileStatic`, a conditional expression whose branches are lambdas 
or method references compiled and then failed when assigned or returned to a 
functional interface:
   
   ```groovy
   @CompileStatic
   Supplier<String> make(boolean flag) {
       Supplier<String> s = flag ? () -> 'a' : () -> 'b'
       s
   }
   make(true).get() // GroovyCastException: Cannot cast object 
'...$$Lambda/...' to class 'groovy.lang.Closure'
   ```
   
   The same held for a conditional expression returned or assigned to a 
subscript, property, field or list element, for method reference branches and 
for a lambda with a closure. Passed as a method argument it worked.
   
   The type checker types the conditional expression as the interface and gives 
each lambda the interface, so each lambda is compiled as an instance of it. 
`BinaryExpressionHelper` takes the common type of the branches from the 
`TypeChooser`, which answered with their inferred type, `Closure` for a lambda, 
and cast each branch to it. `StaticTypesTypeChooser` now resolves a lambda or 
method reference that has a functional interface as its parameter type, which 
is what `StaticTypesLambdaWriter` and 
`StaticTypesMethodReferenceExpressionWriter` compile it to, to that interface.
   
   Assigned to a subscript, a conditional expression with a branch of the 
interface type and a lambda or method reference, such as `map['k'] = flag ? f : 
(String s) -> s.trim()` or `map['k'] = f ?: (String s) -> s.trim()`, did not 
compile: `putAt` was checked with `Object`. The type checker visits the value 
of a subscript assignment before the assignment, and there the lambda got no 
target type, so the common type of the interface and `Closure` was `Object`. 
That visit now takes the subscript's type as the target type of a branch, and a 
method reference branch takes the interface as its type, as a lambda branch 
does.
   
   ## Tests
   
   `TernaryOperatorStaticCompileTest` gets two tests, which fail without the 
change: lambda, method reference and mixed branches assigned to a local 
variable, subscript, property, field and list element, returned, and through an 
Elvis operator; and a branch of the interface type with a lambda assigned to a 
subscript and a property. The full `:test` suite and the lint gate pass. The 
ternary tests also pass with `-Pgroovy.target.lambda.hoist=true 
-Pgroovy.target.closure.pack=true`.
   
   Seen in 6.0.0 and master.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to