我有以下简单的typeclass实现:
sealed trait Foo
object Foo {
case object A extends Foo
case object B extends Foo
}
sealed trait Baz
object Baz {
case object C extends Baz
case object D extends Baz
}
trait TC[C <: Foo, T <: Baz] {
val data: String
}
object instances {
implicit val a: TC[Foo.A.type, Baz.C.type] = new TC[Foo.A.type, Baz.C.type] {
val data = "some data"
}
implicit val b: TC[Foo.A.type, Baz.D.type] = new TC[Foo.A.type, Baz.D.type] {
val data = "some other data"
}
}
object syntax {
def getData[A <: Foo](b: Baz): String =
b match {
case Baz.C => implicitly[TC[A, Baz.C.type]].data
case Baz.D => implicitly[TC[A, Baz.D.type]].data
}
}
我得到以下编译错误:
could not find implicit value for parameter e: TC[A,Baz.C.type]
case Baz.C => implicitly[TC[A, Baz.C.type]].data
难道不可能编写这样一个多态函数并解析类型类实例吗?
您可能想要这样的
trait TC[T <: Foo] {
def getData(b: Baz): String
}
object TC {
def getData[T <: Foo](b: Baz)(implicit ev: TC[T]): String =
ev.getData(b)
implicit final val TCA: TC[A] = {
case C => "Data 1"
case D => "Data 2"
}
// More instances.
}
如果出于任何原因这都不起作用,请告诉我
我可能有一些语法错误,但我希望这个想法是清楚的
这很有效,但我不知道怎么做??
sealed trait Foo
object Foo {
case object A extends Foo
case object B extends Foo
}
sealed trait Baz
object Baz {
case object C extends Baz
case object D extends Baz
}
trait TC[C <: Foo, B <: Baz] {
val data: String
}
object TC {
implicit val a: TC[Foo.A.type, Baz.C.type] = new TC[Foo.A.type, Baz.C.type] {
val data = "some data"
}
implicit val b: TC[Foo.A.type, Baz.D.type] = new TC[Foo.A.type, Baz.D.type] {
val data = "some other data"
}
}
object syntax {
def getData[A <: Foo, B <: Baz](b: B)(implicit ev: TC[A, B]): String = implicitly[TC[A, B]].data
}
syntax.getData(Baz.D) // returns "some other date"