相关疑难解决方法(0)

Scala中的类型模式不考虑继承?

我在某些情况下使用类型类设计API但是我遇到了隐式解析的问题.如下所示,如果存在类型A的隐式对象但是将类型的对象B extends A传递给该方法,则无法找到隐式对象.有没有办法使这项工作或调用者必须将隐式对象放入每个子类的范围?

这是一个例子:

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)
Run Code Online (Sandbox Code Playgroud)

无法使用以下输出进行编译:

/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 …

inheritance scala implicit typeclass

9
推荐指数
2
解决办法
1961
查看次数

标签 统计

implicit ×1

inheritance ×1

scala ×1

typeclass ×1