Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Function - Incompatible Types

Tags:

java

java-8

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.

like image 911
Dave C Avatar asked May 03 '26 16:05

Dave C


1 Answers

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).

like image 67
hoodaticus Avatar answered May 05 '26 05:05

hoodaticus