不兼容的类型java泛型问题

时间:2015-07-07 12:36:44

标签: java generics incompatibletypeerror

我无法理解这个Incompatible types编译错误。

interface Request {}

interface Response {}

class Foo {

   <RQ extends Request, RS extends Response> RS foo(RQ rq) {
      // This doesn't compile: Incompatible types error
      return foo3(foo2(rq));

      /* This compiles fine */ 
      // RS rs = foo2(rq);
      // return foo3(rs);
   }

   <RS extends Response, RQ extends Request> RS foo2(RQ rq) {
      return null;
   }

   <RS extends Response> RS foo3(RS rs) {
      return rs;
   }

对我来说奇怪的是,如果在方法foo中我替换了这个代码,那么代码编译得很好:

return foo3(foo2(rq));

由:

RS rs = foo2(rq);
return foo3(rs);

我肯定错过了什么,但我仍然不明白为什么。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

foo2foo3的{​​{1}}类型参数无关。如果要强制它们相同,请将type参数放在类级别中。

RS

答案 1 :(得分:2)

那是因为在使用

的情况下
RS rs = foo2(rq);
return foo3(rs);

编译器知道哪个具体类型(RS)用于foo2的特化。你告诉它你想要哪种类型。

foo3(foo2(rq));的情况下,编译器无法推断出这一点。因此,Response导致foo2得到不太专业的类型foo3,而RS无法使用class Store < ActiveRecord::Base has_many :orders end

请注意,这种自动扣除是必要的,因为每个方法的类型参数class Order < ActiveRecord::Base has_many :items, :dependent => :delete_all end 都是独立的。没有人保证他们在整个班级中引用相同的类型。如果你希望它们在整个类中是相同的,那么使类本身是通用的,而不是方法。

相关问题