FilipR
FilipR

Reputation: 1238

Java generics: Bound mismatch: The type is not a valid substitute for the bounded parameter of the type

I am facing the following problem:

I have these class & interface definitions

public abstract class ViewModelRefreshPostListFragment<T extends IRefreshPostViewCallback, R extends RefreshPostViewModel<T>>
    extends RefreshPostListFragment implements IRefreshPostView {

    private final ViewModelHelper<T, R> mViewModeHelper = //error here
        new ViewModelHelper<>(); 

...
}

public abstract class RefreshPostViewModel<R1 extends IRefreshPostViewCallback> extends AbstractViewModel<IRefreshPostViewCallback> {}

public class ViewModelHelper<T extends IView, R extends AbstractViewModel<T>> {}

public abstract class AbstractViewModel<T extends IView> {}

public interface IRefreshPostViewCallback extends IView {}

Eclipse gives me still this error: Bound mismatch: The type R is not a valid substitute for the bounded parameter <R extends AbstractViewModel<T>> of the type ViewModelHelper<T,R>

Based on Java inheritance I created these 2 chains:

"Chain" from ViewModelRefreshPostListFragment class definition
1) R extends RefreshPostViewModel<T> -> R extends RefreshPostViewModel<R1 extends IRefreshPostViewCallback> -> R extends AbstractViewModel<IRefreshPostViewCallback>
1.1) T extends IRefreshPostViewCallback
1.2) T (from RefreshPostViewModel<T>) is replaced by <R1 extends IRefreshPostViewCallback> Consitent result from 1.1) and 1.2) so the T parameter should be OK.

"Chain" from ViewModelHelper class definition
2) R extends AbstractViewModel<T>
2.1) T extends IView, IRefreshPostViewCallback extends IView -> T can be replaced by IRefreshPostViewCallback

If I apply 2.1) on 1.1) && 1.2) we see, parameter T is consistent

From 1) follows R extends AbstractViewModel<IRefreshPostViewCallback> from 2) follows R extends AbstractViewModel<T> and from 2.1) follows that T can be replaced by IRefreshPostViewCallback, If I understand the things correctly, this error should not appear, could someone explain me, why is eclipse giving me the error ??

Thank you!

Upvotes: 6

Views: 6416

Answers (1)

rgettman
rgettman

Reputation: 178263

The error message comes from the fact that R is not within its bounds.

Your ViewModelHelper class extends AbstractViewModel<IRefreshPostViewCallback>, no matter what R1 really is.

In the class ViewModelHelper, change the type argument in the extends clause of AbstractViewModel to R1, instead of IRefreshPostViewCallback.

public abstract class RefreshPostViewModel<R1 extends IRefreshPostViewCallback>
    extends AbstractViewModel<R1>

and this will eliminate the error.

This will pass the proper T along in ViewModelHelper. Instead of R being RefreshPostViewModel<IRefreshPostViewCallback>, you will be using RefreshPostViewModel<T>, fulfilling the bounds.

Upvotes: 4

Related Questions