Scott Murphy Heiberg created GROOVY-12822:
---------------------------------------------

             Summary: SC: a conditional expression whose branches are lambdas 
or method references fails when assigned or returned to a functional interface
                 Key: GROOVY-12822
                 URL: https://issues.apache.org/jira/browse/GROOVY-12822
             Project: Groovy
          Issue Type: Bug
            Reporter: Scott Murphy Heiberg


{code:groovy}
import java.util.function.Supplier

@groovy.transform.CompileStatic
Supplier<String> make(boolean flag) {
    Supplier<String> s = flag ? () -> 'a' : () -> 'b'
    s
}
assert make(true).get() == 'a'
{code}

This compiles with 6.0.0 and master, and then fails:
{noformat}
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast 
object 'Script1$$Lambda/0x...' with class 'Script1$$Lambda/0x...' to class 
'groovy.lang.Closure'
{noformat}

The same happens when such a conditional expression is returned, or assigned to 
a subscript, a property, a field or a list element, and when its branches are 
method references or a lambda and a closure:
{code:groovy}
flag ? String::toUpperCase : String::trim
flag ? (String s) -> s + '!' : { String s -> s }
{code}
Passed as a method argument, it works.

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. The 
class generator takes the common type of the branches from their own inferred 
types, which is Closure for a lambda, and casts each branch to it.

Assigned to a subscript, a conditional expression with a branch of the 
interface type and a lambda or method reference does not compile:
{code:groovy}
import java.util.function.Function

@groovy.transform.CompileStatic
Map<String, Function<String, String>> make(Function<String, String> f, boolean 
flag) {
    Map<String, Function<String, String>> map = [:]
    map['ternary'] = flag ? f : (String s) -> s.trim()
    map['elvis'] = f ?: (String s) -> s.trim()
    map
}
{code}
{noformat}
[Static type checking] - Cannot call <V> 
org.codehaus.groovy.runtime.DefaultGroovyMethods#putAt(java.util.Map<? super 
java.lang.String, V>, java.lang.String, V) with arguments 
[java.util.LinkedHashMap<java.lang.String, 
java.util.function.Function<java.lang.String, java.lang.String>>, 
java.lang.String, java.lang.Object]
{noformat}
For a subscript, the type checker visits the value before the assignment, where 
the lambda gets no target type, so the branches' common type is Object. 
Assigned to a local variable, the same expression compiles.




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to