gpt4 book ai didi

scala - 来自 "Beginning Scala"的代码示例中的代码错误

转载 作者:行者123 更新时间:2023-12-04 10:21:11 26 4
gpt4 key购买 nike

尝试运行名为“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))

看起来这是相关的变化:

The Iterator.collect() method in 2.7.7 returns a Seq. In 2.8, it is used to perform a conditional map using a PartialFunction. You can use input.getLines.toSeq instead.

最佳答案

啊,我记得这个:

编辑 : 替换为更深入的答案

The code was written against Scala 2.7.3 and 2.8 introduces some breaking changes.

Here's an update to the code that works under 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

关于scala - 来自 "Beginning Scala"的代码示例中的代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com