0

我有以下地图扩展

object ImplicitMap {
  implicit def extendMap(m : Map[String,Any]) = new MapExtension(m)
}
class MapExtension(m : Map[String,Any]) {
  def +?(conditional:Boolean)(pair:(String,Any)):Map[String,Any] = 
    if (conditional) m + pair
    else m
}

此函数在使用时会给出Boolean does not take parameters的编译时错误,但是书面显式测试(如下)可以正常工作

 test ("Map +?") {

    def +?(conditional:Boolean)(pair:(String,Any)):Map[String,Any] = if (conditional)   Map.empty + pair else Map.empty

    +?(true)("hi" -> 2) should equal (Map("hi" -> 2))
  }
4

1 回答 1

3

我假设您正在尝试编写someMap +? (cond)(pair),但这不起作用,因为它将被评估为someMap.+?(cond(pair)),您必须将其用作普通方法,而不是用作运算符。someMap.+?(cond)(pair)为我工作。

scala> Map("Foo" -> "bar")
res2: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Foo -> bar)

scala> res2.+?(true)(("foo", "bar"))
res3: Map[String,Any] = Map(Foo -> bar, foo -> bar)

scala> res2 +? (true)(("foo", "bar"))
<console>:13: error: Boolean(true) does not take parameters
              res2 +? (true)(("foo", "bar"))
于 2012-05-14T12:42:03.977 回答