我有案例类和每个案例类T我定义一个实体[T]隐式。这些情况下定义一个ID类型是特定于每个T.我然后定义一个抽象表[T]类与检索方法,该方法通过一个投影型T中定义的ID类型的标识符...如何在方法参数中使用泛型类型投影?
但它不工作,我得到类型不匹配:
scalac generic-type-projection.scala
generic-type-projection.scala:31: error: type mismatch;
found : id.type (with underlying type Entity[T]#Id)
required: _5.Id where val _5: Entity[T]
val key = implicitly[Entity[T]].keyFromId(id) // Type mismatch on 'id'.
^
generic-type-projection.scala:41: error: type mismatch;
found : String("dummy")
required: Entity[A]#Id
t.retrieve("dummy")
^
two errors found
下面的代码:
import java.util.UUID
trait Entity[T] {
type Id
type Key
def getId(entity: T): Id
def keyFromId(id: Id): Key
}
case class A(f1: String, f2: Int)
object AImplicits {
implicit object AEntity extends Entity[A] {
type Id = String
type Key = UUID
def getId(entity: A) = entity.f1
def keyFromId(id: String) = UUID.fromString(id)
}
}
object Main {
abstract class Table[T: Entity] {
def store(entity: T): Unit
def retrieve(id: Entity[T]#Id): Option[T]
}
def makeTable[T: Entity]: Table[T] =
new Table[T] {
def store(entity: T): Unit = {}
def retrieve(id: Entity[T]#Id): Option[T] = {
val key = implicitly[Entity[T]].keyFromId(id) // Type mismatch on 'id'.
None
}
}
def main(args: Array[String]) {
import AImplicits._
val t = makeTable[A]
val a = A("dummy", 9)
t.store(a)
t.retrieve("dummy") // Type mismatch on "dummy".
}
}
任何帮助将是非常赞赏。
'def'(实体:E)中的'E':Unit' – stew
对不起,这是一个混淆。应该没有Es,只有Ts。我编辑了代码。谢谢。 – distfp