试图在名为"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))
看起来这是相关的变化:
2.7.7中的Iterator.collect()方法返回一个Seq.在2.8中,它用于使用PartialFunction执行条件映射.您可以改用input.getLines.toSeq.
ont*_*ia_ 14
啊,我记得这个:
编辑:用更深入的答案代替
代码是针对Scala 2.7.3编写的,2.8引入了一些重大更改.
这是对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