在Scala集合的`map`方法上输入推断(2.10.0-RC2)

时间:2012-11-14 07:32:16

标签: scala type-inference

当我这样做时,编译器在p上告诉我“缺少参数类型”:

case class MapResult(input: Any, output: Map[_ <: Any, Any]) {
  override def toString = output.map(p => input + " " + p._1 + " " + p._2 ).mkString("\n")
}    

然后它告诉我

identifier expected but string literal found.
[error]   override def toString = output.map(p: (Any, Any) => input + " " + p._1 + " " + p._2 ).mkString("\n")
                                                                      ^

以下内容:

case class MapResult(input: Any, output: Map[_ <: Any, Any]) {
      override def toString = output.map(p: (Any, Any) => input + " " + p._1 + " " + p._2 ).mkString("\n")
    }

1 个答案:

答案 0 :(得分:2)

只要在函数文字中指定类型参数类型,就需要使用花括号而不是括号:

case class MapResult(input: Any, output: Map[_ <: Any, Any]) {
  override def toString = output.map{p: (Any, Any) => input + " " + p._1 + " " + p._2 }.mkString("\n")
}

更新:您还可以将参数列表包装在括号中,这样即使没有大括号也可以使解析器满意:

case class MapResult(input: Any, output: Map[_ <: Any, Any]) {
  override def toString = output.map( (p: (Any, Any)) => input + " " + p._1 + " " + p._2 ).mkString("\n")
}

在这里你也可以使用模式匹配:

case class MapResult(input: Any, output: Map[_ <: Any, Any]) {
  override def toString = output.map{ case (k: Any, v: Any) => input + " " + k + " " + v }.mkString("\n")
}

至于编译器强迫你在这里指定参数类型的原因,老实说我真的不知道。我无法在scala 2.10-RC1中重现它。