缺少trait Iterator中方法的参数

时间:2012-10-31 16:41:41

标签: scala

我是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))

每次尝试使用命令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

有人能说清楚我在这里做错了吗?

1 个答案:

答案 0 :(得分: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)