假設我在Scala中使用了typeclass模式。以下是我做的類型類美孚的C類 部分:如何將類型類型與子類型相結合?
Welcome to Scala version 2.9.0.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
scala> trait Foo[T] { def foo(t: T) }
defined trait Foo
scala> def foo[T : Foo](t: T) { implicitly[Foo[T]].foo(t) }
foo: [T](t: T)(implicit evidence$1: Foo[T])Unit
scala> class C
defined class C
scala> foo(new C)
<console>:11: error: could not find implicit value for evidence parameter of type Foo[C]
foo(new C)
^
scala> implicit object FooC extends Foo[C] { override def foo(c: C) { println("it's a C!") } }
defined module FooC
scala> foo(new C)
it's a C!
到目前爲止好。但是,假設我有C的子類D,並且我希望D的實例也處於「類」類型中:
scala> class D extends C
defined class D
scala> foo(new D)
<console>:13: error: could not find implicit value for evidence parameter of type Foo[D]
foo(new D)
^
Doh!如何在不需要爲D提供類型實例的情況下進行這項工作?
這是非常HTTP的副本://計算器。 com/questions/3869991/type-class-pattern-in-scala-doesnt-consider-inheritance –