Covariant structure fails with capture-of error in Java

Consider the following Java class definitions: class Animal {} class Lion extends Animal {} When defining a covariant `Cage` for `Animal`s I use this code in Java: class Cage { void add(T animal) { System.out.println("Adding animal..."); } } But the following Java example ... public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ... fails to compile with the following error: > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)
Does your scala code really works? Cage[+T] def add(T) should not compile.

以上就是Covariant structure fails with capture-of error in Java的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏