Mark generic type parameter as functional interface in Java 8 -
i want restrict type parameter of function functional interface.
something this:
public static <@functionalinterface t extends function<a, b>> t foo () { homecoming -> bar; } the @functionalinterface not allowed here.
the aim is, create possible homecoming lambda type of type parameter. since t can normal class, homecoming of lambda not allowed.
is there possibility restrict type parameter functional interface?
as discussed on your other question impossible that. not annotating type parameter implementing unknown interface via lambda expression.
when compiling method
public static <@functionalinterface t extends function<a, b>> t foo() { homecoming -> bar; } the compiler must produce code capable of returning instance of appropriate type doesn’t know t depends on caller of foo() there no connection between compiling foo() , compiling caller of foo(). latter might happen years later on other side of our planet.
maybe not aware of type erasure. there 1 compiled version of method foo() has fulfill generic contract of returning instance of appropriate type. without knowing what t is.
this works when returning existing instance when returning element of collection or 1 of values passed parameters. generic methods unable homecoming new instances of type parameter. not using new , neither using lambda expression.
note still possible have sub-interface implementations of desired function if allow caller knows type perform “up-level” operation. suppose have generic mill method like:
public static <a,b> function<a,b> getter(map<?, ? extends b> map) { homecoming a->map.get(a); } this code works unknown types a , b , unknown parametrization of map because constraint method map.get accepts instances of a accepts anything , returns instance of b type ? extends b assignable b.
now, if caller has arbitrary sub-type of function, x, e.g.
interface x extends function<string, integer> {} it can utilize mill method produce instance of x decorates function, like:
map<string, integer> map=new hashmap<>(); x x=getter(map)::apply; x.apply("foo"); here, constraint on x beingness functional interface checked on caller site.
java generics lambda java-8 java-stream
No comments:
Post a Comment