2

我是 Scala 的新手,正在阅读《Beginning Scala》一书,但我似乎无法找到一个有效的示例。我已经检查了很多次,但似乎找不到我的代码偏离的地方。我有以下 scala 文件:

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

val input = Source.fromInputStream(System.in)
val lines = input.getLines.collect

println("Sum "+sum(lines))

每次我尝试使用 command 运行时Scala sum.scala,都会收到以下错误:

sum.scala:18: 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

谁能阐明我在这里做错了什么?

4

1 回答 1

2

你到底想收集什么?要获得每行数字的总和,无需调用 collect:

val lines = input.getLines.toList
println("Sum "+sum(lines))

或通过标准 scala 函数:

val numbers = input.getLines.map(line => line.trim.toInt)
println("Sum "+numbers.sum)
于 2012-10-31T16:50:43.423 回答