【问题标题】:missing arguments for method in trait Iterator特征迭代器中的方法缺少参数
【发布时间】:2012-11-01 00:57:47
【问题描述】:

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

谁能解释一下我在这里做错了什么?

【问题讨论】:

    标签: scala


    【解决方案1】:

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

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

    或通过标准的scala函数:

    val numbers = input.getLines.map(line => line.trim.toInt)
    println("Sum "+numbers.sum)
    

    【讨论】:

    • 我将 .collect 更改为 .toList 并且一切正常 - 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2021-07-24
    • 2019-10-23
    相关资源
    最近更新 更多