开发者

Scala abstract path dependent type problem

Does anyone know what's going on here with this compiler error? The error goes away if I don't extend INode.

trait AbsTypes
{
    type TKey
    type TValue
}

trait INode extends AbsTypes
{
    def get(key : TKey) : TValue
    def set(key : TKey, v : TValue) : INode
}

class ANode[TKey,TValue](
  val akey : TKey,
  val aval : TValue
) extends INode
{
    // ERROR : type mismatch;  found   : ANode.this.aval.type (with underlying type TValue)  required: ANode.this.TValue
    def get(key : TKey) : TValue = { aval }
    def set(key : TKey, v : TValue开发者_运维百科) : INode = {
        new ANode(key,v)
    }
}


Generic parameters don't automatically override abstract types, even if they have the same names. Try renaming the generic parameters (to avoid name conflicts), and then declaring the types TKey and TValue in the method body.

class ANode[A,B](
  val akey : A,
  val aval : B
) extends INode {
    type TKey=A
    type TValue=B
    def get(key : TKey) : TValue =  aval 
    def set(key : TKey, v : TValue) : INode = new ANode(key,v)
}

I suppose it would be nice if the compiler emitted an error on the line where you specified the names of the generic types, instead of waiting until you started using those types.


I don't have time unfortunately to test what I'm about to write but my understanding of your code is that each INode is going to get it's own TValue type. So the get operation really returns INode.this.TValue which is not compatible with another TValue type on another node.

The way to avoid this might be to write:

trait Nodes {
  type TKey
  type TValue

  trait INode {
   def get(key : TKey) : TValue
  }

  class ANode(
    val akey : TKey,
    val aval : TValue
  ) extends INode
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜