我有一个编译器 类型不匹配错误 我不明白。
鉴于 Elem
的以下定义和一个工厂( Companion
):
object Elem {
trait Companion[E[~] <: Elem[~]] {
def apply[S](peer: E[S]#Peer): E[S] // wrap a peer in its elem
}
}
trait Elem[S] {
type Peer
}
并给出例如
Obj
具有属性和对等类型 Expr
:trait Expr[S, A]
trait Obj[S] {
// query an attribute by key
def attr[E[~] <: Elem[~]](key: String)
(implicit c: Elem.Companion[E]): Option[E[S]#Peer]
}
我应该能够做到以下几点:
// process elements with peer `Expr[~, A]`
trait Impl[S, A, E[~] <: Elem[~] { type Peer = Expr[~, A] }] {
implicit def companion: Elem.Companion[E]
def test(obj: Obj[S]): Unit =
obj.attr[E]("foo").fold(()) { ex =>
val newElem = companion[S](ex)
}
}
最后一点失败并显示出色的错误消息:
<console>:62: error: type mismatch;
found : E[S]#Peer
(which expands to) Expr[S,A]
required: E[S]#Peer
(which expands to) Expr[S,A]
val newElem = companion[S](ex)
^
最佳答案
我将您的示例简化为以下内容:
trait Elem {
type Peer
}
trait Impl[E[~] <: Elem {type Peer = ~}] {
def foo[R](peer: E[R]#Peer)
foo[Int](??? : E[Int]#Peer)
}
scalac 给出的地方
Error:(12, 18) type mismatch;
found : this.scala.Peer
(which expands to) Int
required: this.Peer(in method foo)
(which expands to) R
foo[Int](??? : E[Int]#Peer)
^^
我不确定,但这看起来像是 Scala 错误,因为
R
甚至不在错误现场的范围内 - 它似乎已经泄漏了。 Scala 似乎无法执行替换 R = Int
在细化内部,允许参数R
保持。
关于scala - 类型与类型投影不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945416/