Paul King created GROOVY-12727:
----------------------------------

             Summary: STC: a generic method's type parameter isn't inferred 
from the return-type target when the argument is a lambda
                 Key: GROOVY-12727
                 URL: https://issues.apache.org/jira/browse/GROOVY-12727
             Project: Groovy
          Issue Type: Bug
            Reporter: Paul King


Under {{@TypeChecked}} (and {{@CompileStatic}}), when a generic method's only 
argument is an implicitly typed lambda, the type parameter is not inferred from 
the expected return type. The lambda's parameter is typed with a wildcard 
({{Ctx<? extends Object>}}), and a call inside the lambda that needs the 
concrete type is rejected. javac infers {{T = String}} from the return-type 
target and compiles the equivalent Java.

This is the standard Apache Pekko (and Akka) typed-actor factory, 
{{Behaviors.setup(context -> new MyActor(context))}}, so statically compiled 
Pekko code needs a type witness or an explicitly typed lambda parameter.

h3. Repro (no dependencies)

{code:groovy}
import java.util.function.Function
import groovy.transform.TypeChecked

class Ctx<T> {}
class Beh<T> {}
class Behaviors {
    static <T> Beh<T> setup(Function<Ctx<T>, Beh<T>> factory) { 
factory.apply(new Ctx<T>()) }
}
class Bot extends Beh<String> {
    Bot(Ctx<String> c, int max) {}
}
@TypeChecked
class M {
    static Beh<String> lambda(int max) { Behaviors.setup(c -> new Bot(c, max)) }
}
{code}

h3. Actual

{noformat}
[Static type checking] - Cannot call Bot#<init>(Ctx<java.lang.String>, int) 
with arguments [Ctx<? extends java.lang.Object>, int]
{noformat}

h3. Expected

Compiles, as the Java equivalent does with javac ({{T}} inferred as {{String}} 
from the {{Beh<String>}} return type).

h3. Workarounds (both compile on 6.0.0)

{code:groovy}
Behaviors.<String>setup(c -> new Bot(c, max))                 // explicit type 
witness
Behaviors.setup((Ctx<String> c) -> new Bot(c, max))          // explicitly 
typed lambda parameter
{code}

h3. Notes

* The closure form, {{Behaviors.setup { c -> new Bot(c, max) }}}, fails with 
the same message.
* An assignment target fails the same way as a return target: {{Beh<String> b = 
Behaviors.setup(c -> new Bot(c, max))}}.
* Possibly related, not duplicates:
** GROOVY-11446: target-type handling for a generic method with wildcards, in 
the opposite direction (accepted when it should fail).
** GROOVY-11077: lambda parameter types from a wildcard SAM; no generic method 
or inference involved.
** GROOVY-12714 / PR #3246: javac-compatibility changes to wildcard containment 
in the same visitor; they don't appear to supply this inference (not verified 
against the branch).




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

Reply via email to