Java 8 Feature - Incompatible Types

I am trying to assign a java 8 function pointer to a variable, but creating an incompatible type error. It looks like the compiler is not honoring the "? Extends BaseEntity".

For the code below, ChildEntity extends BaseEntity directly:

private int getValue(ChildEntity entity) {
    return 0;

Function<? extends BaseEntity, ?> function = this::getValue;


Error: The underlying object could not be converted to a ChildEntity.


source to share

4 answers

Think about how it will be used function

. You are going to pass in it an object of any type that inherits from BaseEntity


Imagine what SpouseEntity

also comes directly from BaseEntity

. Could you pass this SpouseEntity

to the method that requires it ChildEntity


No, you wouldn't do that because it SpouseEntity

didn't come out ChildEntity


In other words, the method pointed to by a function pointer must have its parameters no more than those specified in the function pointer itself. The parameters of a function pointer must be obtained or identical to those specified in the method it points to.

(Note that the return type of text works in exactly the opposite way, so it super

exists because the return type of a method must inherit or be identical to the return type of its function pointer).



ChildEntity extends BaseEntity, so not everything that extends BaseEntity is a valid argument to your function. You can do:

Function<ChildEntity, int> function = this::getValue;



Function<? extends ChildEntity, int> function = this::getValue;




? super BaseEntity

won't work because it BaseEntity

doesn't expand ChildEntity

(in fact, the opposite is true).

? extends BaseEntity

won't work because we don't really know what type the BaseEntity

function will accept. As a caller, I don't know if it is safe to pass tags ChildEntity

, a BaseEntity

, a SomeOtherTypeOfEntity

or whatever.



The Remeber key this

applies to the class you are currently working in. Therefore, if BaseEntity does not have a method getValue(ChildEntity)

, anything that extends BaseEntity will most likely fail. Modify the function to require a class that extends ChildEntity. You are also missing your return type.



All Articles