我在某些情况下使用类型设计API,但是我遇到了隐式解决方案的问题。如下所示,如果存在类型A的隐式对象,但类型B extends A
的对象被传递给该方法,则无法找到隐式对象。有没有办法让这个工作或调用者必须将隐式对象放入每个子类的作用域中?在Scala中输入类模式不考虑继承?
下面是一个例子:
class A
class B extends A
class T[+X]
object T {
implicit object TA extends T[A]
}
def call[X:T](x:X) = println(x)
// compiles
call(new A)
// doesn't compile
call(new B)
var a = new A
// compiles
call(a)
a = new B
// compiles
call(a)
val b = new B
// doesn't compile
call(b)
这失败与以下输出编译:
/private/tmp/tc.scala:16: error: could not find implicit value for evidence parameter of type this.T[this.B] call(new B) ^ /private/tmp/tc.scala:28: error: could not find implicit value for evidence parameter of type this.T[this.B] call(b)
我也尝试将调用的定义更改为: def call [X,X2 <:X](x:X2) (隐含x2:T [X])= println(x) 而这并没有帮助 – 2010-10-06 06:41:13