我有以下代码定义类型类。类型类和子类型
trait Foo[T] {
def toFoo(x: T): String
}
trait Foos {
def toFoo[T](f: T => String): Foo[T] = new Foo[T] {
def toFoo(x: T): String = f(x)
}
}
object Foo extends Foos {
def toFoo[A: Foo](a: A) = implicitly[Foo[A]].toFoo(a)
implicit def AToFoo: Foo[A] = toFoo { c =>
"A"
}
implicit def BToFoo[T]: Foo[B] = toFoo { c =>
"B"
}
implicit def ListToFoo[T: Foo]: Foo[List[T]] = toFoo { c =>
c.map(toFoo(_)).
}
}
class A
class B extends A
现在如果我有,如果我做toFoo(List(new A, new B)
我得到List("A", "A")
而不是List("A", "B")
。如何确保使用BtoFoo
方法,而不是AToFoo
用于类型B
的类?
你期望'List(new A,new B)'有什么类型? – 2012-03-20 13:59:02
我希望'List(new A,new B)'有类型'List [A]' – Stephan 2012-03-22 09:16:48
在这种情况下,当您将'toFoo'映射到'List [A]'上时,它显然首先执行'Flicit [Foo [A]]'并获取'AToFoo'隐式def,并将其用于每个元素。类型类专为类型定向调度而设计,而不是用于价值定向调度,所以它们并不总是很好地与子类型匹配。 – 2012-03-22 18:07:27