scala - 类型与类型投影不匹配

标签 scala path-dependent-type type-projection

我有一个编译器 类型不匹配错误 我不明白。

鉴于 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/

相关文章:

json - 在Scala的剧本中使用Json序列化处理具有多个案例类(和类型)的特质

scala - 编译器似乎忽略类型细化中的类型绑定(bind)

scala - 如何从投影类型推断正确的类型参数?

scala - 通过Spark写入HBase : Task not serializable

scala - 理解与子类的模式匹配

java - 如何在外部组件上发生事件时立即检测到该事件。不想投票,还有其他选择吗?

scalaz.Equal 用于路径依赖类型

scala - Scala 的路径依赖类型是什么意思?

scala - scala中 `type`和 `#`关键字的调查

scala - 引用类型参数的抽象类型成员