【发布时间】:2014-09-17 10:56:55
【问题描述】:
假设我有任意单参数泛型类的实例(我将在演示中使用List,但这可以是任何其他泛型)。
我想编写可以接受实例 (c) 并能够理解什么泛型类 (A) 和什么类型参数 (B) 生成类 (C) 的泛型函数那个实例。
我想出了这样的东西(函数的主体并不真正相关,但证明C符合A[B]):
def foo[C <: A[B], A[_], B](c: C) {
val x: A[B] = c
}
... 如果您像这样调用它,它会编译:
foo[List[Int], List, Int](List.empty[Int])
...但是如果我省略显式类型参数并依赖推理,编译会失败并出现错误:
foo(List.empty[Int])
我得到的错误是:
Error:Error:line (125)inferred kinds of the type arguments (List[Int],List[Int],Nothing) do not conform to the expected kinds of the type parameters (type C,type A,type B).
List[Int]'s type parameters do not match type A's expected parameters:
class List has one type parameter, but type A has one
foo(List.empty[Int])
^
Error:Error:line (125)type mismatch;
found : List[Int]
required: C
foo(List.empty[Int])
^
正如您所见,在这种情况下,Scala 的类型推断无法正确推断类型(似乎猜测第二个参数是 List[Int] 而不是 List,第三个参数是 Nothing 而不是 Int)。
我假设我想出的foo 的类型边界不够精确/正确,所以我的问题是如何实现它,以便 Scala 可以推断参数?
注意:如果有帮助,可以假设所有潜在的泛型 (As) 继承/符合某些共同祖先。例如,A 可以是继承自 Seq 的任何集合。
注意:此问题中描述的示例是合成的,是我要解决的更大问题的提炼部分。
【问题讨论】: