1

Imagine I extended the List interface to add a method as follows:

public interface MyList<E> extends List<E> {

    <R super E> MyList<R> castTo(Class<R> klass);

}

Why is this illegal? Am I just doing it in the wrong way because you should definitely be able to do this.

for example I would like to do something like the following:

MyList<? extends X> someList = // list from somewhere
MyList<X> xs = someList.castTo(X.class)
th0masb
  • 303
  • 1
  • 11
  • you mean `` not `` – Youcef LAIDANI May 15 '18 at 10:11
  • 1
    @YCF_L no I don't. I want to upcast the List – th0masb May 15 '18 at 10:12
  • Also read this https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java – Youcef LAIDANI May 15 '18 at 10:13
  • They don't answer my question. I should be allowed to upcast to Object if I so desired. It does not contradict anything. – th0masb May 15 '18 at 10:18
  • The "Bounding generics with 'super' keyword" seems to be a bit array-heavy. In this example, there are no arrays. Will not vote to close as duplicate. – Andrey Tyukin May 15 '18 at 10:19
  • @Someguy "I should be allowed to upcast to Object if I so desired." So then make the return type `List` – Michael May 15 '18 at 10:19
  • @Michael I was just commenting on why one of the resons in another answer doesn't apply. I should be allowed to upcast to any superclass. – th0masb May 15 '18 at 10:21
  • 1
    Afraid I dupe-hammered it as the other answers *do* apply, as far as they can. (The upshot is there's nothing *logically* wrong with what you're doing, but the spec disallows it - probably because there's relatively few cases where it would be useful, and more cases where it could cause issues.) – Michael Berry May 15 '18 at 10:30

0 Answers0