0

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")
    }
4

1 回答 1

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 中重现它。

于 2012-11-14T08:07:26.353 回答