Scott Murphy Heiberg created GROOVY-12607:
---------------------------------------------
Summary: STC accepts a method pointer or method reference whose
method return type does not fit the target functional interface
Key: GROOVY-12607
URL: https://issues.apache.org/jira/browse/GROOVY-12607
Project: Groovy
Issue Type: Bug
Affects Versions: 5.0.8, 4.0.33, 6.0.0
Reporter: Scott Murphy Heiberg
{code:groovy}
import java.util.function.Supplier
@groovy.transform.CompileStatic
class C {
int intMethod() { 1 }
Supplier<String> f() { this.&intMethod }
String take(Supplier<String> s) { s.get() }
def g() { take(this::intMethod) }
def h() { Supplier<String> s = this::intMethod; s.get().toUpperCase() }
}
new C().h()
{code}
Actual: the class compiles. At run time the supplier returns an Integer, so the
script fails with {{ClassCastException: class java.lang.Integer cannot be cast
to class java.lang.String}} (under @TypeChecked: MissingMethodException for
toUpperCase on Integer). The same happens for a Boolean supplier from a
String-returning method and a Long supplier from an int-returning method, with
.& or ::, returned, passed or assigned. A method pointer (.&) that is returned
or assigned is not checked at all, so even a method returning an Integer
supplier as this.&stringMethod compiles.
Expected: a compile error such as "Invalid return type: int is not convertible
to java.lang.String", as for the equivalent lambda.
Cause: the return-type check for method pointers and references uses assignment
compatibility, which allows conversions (to String, Boolean, wider number
wrappers) that a method pointer or reference never performs. A method pointer
gets no target type when it is returned or assigned.
Seen in 4.0.33, 5.0.8 and 6.0.0.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)