加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:22:09 所属栏目:安全 来源:网络整理
导读:试图在名为“Beginning Scala”的Apress书中运行示例代码.我甚至从他们的网站下载了代码,以确保我没有.获取以下消息: /root/sum.scala:19: error: missing arguments for method collect in trait Iterator;follow this method with `_' if you want to tre
试图在名为“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读