当我这样做时,编译器在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")
}
答案 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中重现它。