I am attempting to assign a java 8 function pointer to a variable but get an incompatible type error when building. It appears that the compiler is not respecting "? extends BaseEntity".
For the below code ChildEntity directly extends BaseEntity:
private int getValue(ChildEntity entity) {
return 0;
}
Function<? extends BaseEntity, ?> function = this::getValue;
Error: Base entity can not be converted to a ChildEntity.
Think about how function will be used. You are going to pass into it an object of any type that inherits from BaseEntity.
Imagine SpouseEntity also derives directly from BaseEntity. Would you be able to pass that SpouseEntity into a method that requires a ChildEntity?
No, you would not, because SpouseEntity did not derive from ChildEntity.
In other words, the method pointed to by a function pointer must have its parameters be no more derived than those declared in the function pointer itself. The function pointer parameters must derive from, or be identical to, those declared in the method it points to.
(Note that return type works the exact opposite way, which is why super exists, because the return type of a method must inherit from or be identical to the return type of its function pointer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With