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 {
^
如何解决?
答案 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)