“Beginning Scala”代码示例中的代码错误

问题描述:

尝试运行名为“Beginning Scala”的Apress书中的示例代码。我甚至从他们的网站下载了代码,以确保我没有混淆。获得以下消息:“Beginning Scala”代码示例中的代码错误

/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 

,这里是我使用(运行斯卡拉版2.8.1.final(Java的热点(TM)服务器VM,在Fedora 13)的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)) 
源代码

看起来这是相关的变化:。

在2.7.7回报序列的Iterator.collect()方法在2.8,它是用来使用PartialFunction执行条件地图你可以使用input.getLines.toSeq代替。

+0

这是错的太多的方法让我通过我的电话做出回应。作为一个快速和肮脏的修复,尝试简单地删除该行末尾的'.collect'。 – 2011-05-17 22:46:51

嗯,我记住这一点:

编辑:深入回答更多的替代

的代码编写针对斯卡拉 2.7.3和2.8引入了一些重大变化。

这里有一个更新的代码,斯卡拉下 工程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

+2

+1:不幸的是,语言的发展速度比书籍更快。 – 2011-05-17 22:56:28

+3

看起来像这是相关的变化:2.7.7中的Iterator.collect()方法返回一个Seq。在2.8中,它用于使用PartialFunction执行条件映射。 您可以改为使用input.getLines.toSeq。 – Ramy 2011-05-18 00:31:14

+0

是不是^ Z在窗户上,而不是^ C? – vy32 2015-10-19 01:06:01