来自“Beginning Scala”的代码示例中的代码错误
试图在名为“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)) 看起来这是相关的变化:
解决方法
啊,我记得这个:
编辑:更深入的答案取代
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |