scala,向Map类添加一个隐式函数,失败了“结构细化可能不会引用一个抽象”

时间:2014-01-01 16:41:09

标签: scala

  import scala.language.implicitConversions

  implicit def extendedMap[A,B](map: Map[A,B]) = new {
    def updatedOption(key: A, valueOption: Option[B]) = valueOption match {
      case Some(value) => map.updated(key, value)
      case None => map - key
    }
  }

  var kv = Map.empty[String, String]
  kv.updatedOption("k1", Some("v1")

  //removing the implicit keyword, and explicitly calling the conversion also fails:
  extendedMap(kv).updatedOption("k1", Some("v1")

错误编译器消息:

Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
    def updatedOption(key: A, valueOption: Option[B]) = valueOption match {

                  ^

如何解决?

1 个答案:

答案 0 :(得分:2)

由于scala 2.10您不应将implicit def用于extension methods - 请改用implicit class。见SIP-13。使用implicit class,您不应导入language.implicitConversions

implicit class ExtendedMap[A,B](map: Map[A,B]) {
  def updatedOption(k: A, v: Option[B]) = v.map{ map.updated(k, _) }.getOrElse(map - k)
}

实际上它应该与implicit def一起使用这样的显式类声明:

class ExtendedMap[A,B](map: Map[A,B]) {
  def updatedOption(k: A, v: Option[B]) = v.map{ map.updated(k, _) }.getOrElse(map - k)
}
implicit def toExtendedMap[A,B](map: Map[A,B]): ExtendedMap[A,B] =
  new ExtendedMap[A, B](map)