尝试在名为“Beginning Scala”的Apress书中运行示例代码。我甚至从他们的网站下载了代码,以确保我没有傻瓜。获得以下消息:
/root/sum.scala:19: error: missing arguments for method collect in trait Iterator;
follow this method with `_' if you want to treat it as a partially applied function
val lines = input.getLines.collect
^
one error found
这是我使用的源代码(在Fedora 13上运行Scala版本2.8.1.final(Java HotSpot(TM)Server VM,Java 1.6.0_22)
import scala.io._
def toInt(in: String): Option[Int] =
try {
Some(Integer.parseInt(in.trim))
} catch {
case e: NumberFormatException => None
}
def sum(in: Seq[String]) = {
val ints = in.flatMap(s => toInt(s))
ints.foldLeft(0)((a, b) => a + b)
}
println("Enter some numbers and press ctrl-D (Unix/Mac) ctrl-C (Windows)")
val input = Source.fromInputStream(System.in)
val lines = input.getLines.collect
println("Sum "+sum(lines))
看起来这是相关的变化:
2.7.7中的Iterator.collect()方法返回一个Seq。在2.8中,它用于使用PartialFunction执行条件映射。 您可以改用input.getLines.toSeq。
答案 0 :(得分:14)
编辑 :替换为更深入的答案
代码是针对Scala编写的 2.7.3和2.8引入了一些重大变化。
这是对代码的更新 在Scala 2.8.0下工作:
import scala.io._
object Sum {
def main(args: Array[String]): Unit = {
println("Enter some numbers and press ctrl-D (Unix/Mac) ctrl-Z (Windows)")
val input = Source.fromInputStream(System.in)
val lines = input.getLines.toList
println("Sum " + sum(lines))
}
def toInt(s: String): Option[Int] = {
try {
Some(Integer.parseInt(s))
} catch {
case e: NumberFormatException => None
}
}
def sum(in: Seq[String]): Int = {
val ints = in.flatMap(toInt(_))
ints.foldLeft(0)((a, b) => a + b)
}
}
来源:http://scala-programming-language.1934581.n4.nabble.com/Beginning-Scala-book-problem-td2966867.html