scala - 在文件中的字符上使用迭代器时,scala 中的令人惊讶的行为

标签 scala

在迭代文本文件的字符时,我遇到了一些不一致的行为。

以下脚本

import io.Source
val source = Source.fromFile("blah")
val iter = source.buffered
iter.dropWhile(_.isWhitespace)
for( c <- iter ) {
    println("""char="%c", byte=%d, isWhitespace=%b""".format(c, c.toByte, c.isWhitespace))
}
source.close()

读取以下文件(以 3 个空格开头,然后是“a”和第二行文本)

   a
bc de

输出以下内容

char=" ", byte=32, isWhitespace=true
char=" ", byte=32, isWhitespace=true
char=" ", byte=32, isWhitespace=true
char="a", byte=97, isWhitespace=false
char="
", byte=10, isWhitespace=true
char="b", byte=98, isWhitespace=false
char="c", byte=99, isWhitespace=false
char=" ", byte=32, isWhitespace=true
char="d", byte=100, isWhitespace=false
char="e", byte=101, isWhitespace=false
char="
", byte=10, isWhitespace=true

dropWhile(_.isWhitespace) 没有删除 3 个空格,但 c.isWhitespace 在紧随其后的 for 循环中迭代时返回 true。

有人可以帮我解释一下吗?我已经在十六进制编辑器中打开了文本文件,它对我来说看起来没问题(纯 ascii,没有 UTF 内容)。

编辑:在 Ubuntu 上使用 Scala 2.9.2

EDIT2:现在我很困惑。以下内容来自 Windows 7 上的 REPL:

c:\projects\scratch>scala
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val it = Iterator("a", "b", "cde", "f")
it: Iterator[String] = non-empty iterator

scala> val it2 = it.dropWhile(_.length < 2)
it2: Iterator[String] = non-empty iterator

scala> println(it.next)
cde

scala> println(it2.next)
f

将这段代码作为脚本运行,会产生原始问题的行为(迭代器不会被 dropWhile 修改)。

最佳答案

在 scala 中,val 是不可变的对象。一旦设置了 val,就无法更改。当您调用 iter.dropWhile(_.isWhitespace) 时,会创建一个新对象,但不会存储在任何地方。如果您想删除空格,您应该将 iter.dropWhile(_.isWhitespace) 分配给一个新 val 并在 for 表达式中调用这个新 val。

关于scala - 在文件中的字符上使用迭代器时,scala 中的令人惊讶的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19210551/

相关文章:

scala - 为什么我应该使用 object vs trait Dependencies 并导入它 vs mixin 来构建定义?

scala - Spark Scala:无法导入sqlContext.implicits._

scala - 这个三元运算符的实现是如何工作的?

scala - 从哪里开始依赖类型编程?

mongodb - 如何使用 Scala 将 1 亿条记录加载到 MongoDB 中进行性能测试?

java - Microsoft SQL 和 JDBC 中 Prepared Statements 中奇数位置的参数

android - 找不到库 "libmaliinstr.so"

scala - Some(Array(Array(Array(String)))) 到 Array(String) 的转换/扁平化

java - scala 覆盖引用内部类的 java 类方法

scala - 将隐式 ExecutionContext 传递给包含的对象/调用的方法