我有以下关系:
SomeClass.h
我有以下情况:
trait Bar[I <: Foo] { def doSomething(...) }
object Doer { def apply[I <: Foo](...)(implicit ev: Bar[I]) = ev.doSomething(...) }
trait Foo
case class A(...) extends Foo
object A { implicit object Something extends Bar[A] }
case class B(...) extends Foo
object B { implicit object SomethingElse extends Bar[B] }
不使用val xs: List[Foo] = ...
xs.map(x => Doer(x)) // implicit not found since no implementation for type Foo.
,因为它会破坏为将来扩展性提供类型类的整个想法。
我需要做什么才能处理这种情况?
答案 0 :(得分:2)
问题中可以看到两个主要困难
但是想象一下我们有这样的定义
trait Bar[+I] {def doSomething[J >: I](x: J): String}
object Doer {
def apply[I <: Foo](el: I)(implicit ev: Bar[I]) = ev.doSomething(el)
}
trait Foo
case class A() extends Foo
object A {
implicit object Something extends Bar[A] {
def doSomething[X >: A](el: X) = "do A"
}
}
case class B() extends Foo
object B {
implicit object SomethingElse extends Bar[B] {
def doSomething[X >: B](el: X) = "do B"
}
}
我们可能会创建一些数据类型来保持已解决的含义:
case class MemoTC[+Value, TC[+_]](value: Value)(implicit tc: TC[Value]) {
def withTC[Result](action: (Value) ⇒ TC[Value] ⇒ Result): Result =
action(value)(tc)
}
现在你可以编写奇怪的代码,比如
val xs: List[MemoTC[Foo, Bar]] = List(MemoTC(A()), MemoTC(B()))
xs.map(x => x.withTC( x ⇒ implicit bar ⇒ Doer(x) ))
如果你想保持你的类型类不变,这个例子也可以在存在类型的帮助下进行调整:
trait Bar[I] {def doSomething(x: I): String}
object Doer {
def apply[I <: Foo](el: I)(implicit ev: Bar[I]) = ev.doSomething(el)
}
trait Foo
case class A() extends Foo
object A {
implicit object Something extends Bar[A] {
def doSomething(el: A) = "do A"
}
}
case class B() extends Foo
object B {
implicit object SomethingElse extends Bar[B] {
def doSomething(el: B) = "do B"
}
}
abstract class MemoTC[Abstract, TC[_]] {
type Concrete <: Abstract
val value: Concrete
val inst: TC[Concrete]
def withTC[Result](action: (Concrete) ⇒ TC[Concrete] ⇒ Result): Result =
action(value)(inst)
}
object MemoTC {
def apply[A, C <: A, TC[_]](v: C)(implicit tc: TC[C]) = new MemoTC[A, TC] {
type Concrete = C
val value = v
val inst = tc
}
}
val xs: List[MemoTC[Foo, Bar]] = List(MemoTC(A()), MemoTC(B()))
xs.map(x => x.withTC(x ⇒ implicit bar ⇒ Doer(x)))