【发布时间】:2013-12-26 17:46:17
【问题描述】:
我有案例类,并且为每个案例类 T 我定义了一个 Entity[T] 隐式。这些实例定义了一个特定于每个 T 的 Id 类型。然后我定义了一个带有检索方法的抽象 Table[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".
}
}
非常感谢任何帮助。
【问题讨论】:
-
E中的def store(entity: E): Unit是什么 -
对不起,这是一个混淆。应该没有Es,只有Ts。我编辑了代码。谢谢。
标签: scala generics types projection