繁体   English   中英

Scala:通过特征扩展 Map 时出现“不兼容的类型”错误

[英]Scala: "Incompatible type" error when extending Map via a trait

我有一个 class 基本上是一个Map有一些额外的方法。 我通过包装常规Map来实现它,如下所示:

class IntIntMap private (
  val delegate: Map[Int, Int]
) extends Map[Int, Int] with MapLike[Int, Int, IntIntMap] {
  def extraMethod: Unit = println("Test!")
  // Method overrides from MapLike
  // CanBuildFrom, implicit conversions, etc. in the companion object
}

这很好用; 然而,后来我发现我需要两个不同的类来处理相同的数据:一个类似于地图的类用于组装数据,一个优化版本用于访问它。 我想我可以将额外的部分分解为一个特征:

trait IntIntTrait extends Map[Int, Int] with MapLike[Int, Int, IntIntTrait] {
  def extraMethod: Unit
}

class IntIntMap private (
  val delegate: Map[Int, Int]
) extends IntIntTrait {
  override def extraMethod: Unit = println("Test!")
  // Method overrides from MapLike
  // CanBuildFrom, implicit conversions, etc. in the companion object
}

class OtherImplementation extends IntIntTrait { ... }

不幸的是,这不起作用,因为我收到以下错误: overriding method empty in trait MapLike of type => IntIntMap; method empty in trait Map of type => scala.collection.Map[Int, Int] has incompatible type overriding method empty in trait MapLike of type => IntIntMap; method empty in trait Map of type => scala.collection.Map[Int, Int] has incompatible type

我尝试将MapLike从特征移动到 class,但仍然导致相同的错误。 我还尝试使用MapLike[Int, Int, Map[Int, Int]]来定义它,它可以编译,但随后filter等返回Map[Int, Int] ,而不是IntIntMap

我错过了什么?

您的第一个片段也不起作用。 像这样扩展Map是……困难的。 我可能可以完成,但对于您的目的而言,几乎可以肯定这太复杂了。

我会坚持隐式扩展:

 object MapOps {
    implicit class IntIntMap(val delegate: Map[Int, Int]) extends AnyVal {
      def extraMethod: Unit = println("Test!")
    } 
 }

这将extraMethod添加到任何Map[Int, Int]

   import MapOps._
   Map(1 -> 1).extraMethod

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM