for 循环中的 Scala println
下面的 Scala 代码正如我所期望的那样 - 它打印 some_file.txt 的每一行。
import scala.io.Source
val lines = Source.fromPath("some_file.txt").mkString
for (line <- lines) print(line)
如果我使用 println 而不是 print,我希望看到 some_file.txt 以双倍行距打印出来。相反,程序会在 some_file.txt 的每个字符后打印一个换行符。有人可以向我解释一下吗?我正在使用 Scala 2.8.0 Beta 1。
The following Scala code does just what I expect it to - it prints each line of some_file.txt.
import scala.io.Source
val lines = Source.fromPath("some_file.txt").mkString
for (line <- lines) print(line)
If I use println instead of print, I expect to see some_file.txt printed out with double-spacing. Instead, the program prints a newline after every character of some_file.txt. Could someone explain this to me? I'm using Scala 2.8.0 Beta 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
lines
是单个字符串,而不是某个可迭代的字符串容器。这是因为您调用了.mkString
方法。当您迭代一个字符串时,您一次会迭代一个字符。因此,
for
中的line
实际上并不是一行,而是单个字符。您可能想要做的是调用
.getLines
而不是.mkString
lines
is a single string, not some iterable container of strings. This is because you called the.mkString
method on it.When you iterate over a string, you do so one character at a time. So the
line
in yourfor
is not actually a line, it's a single character.What you probably intended to do was call
.getLines
instead of.mkString
我怀疑
for (line <-lines) print(line)
不会在line
中放置一行,而是放置一个字符。由于\n
也在那里,所以输出符合预期。当您将print
替换为println
时,每个字符都会获得自己的行。I suspect that
for (line <- lines) print(line)
doesn't put a line inline
but instead a character. Making the output as expected since the\n
is there too. When you the replace theprint
withprintln
every character gets its own line.