scala for循环中的Scala println
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2442030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala println in a for loop
提问by user293361
The following Scala code does just what I expect it to - it prints each line of some_file.txt.
下面的 Scala 代码正是我所期望的——它打印了 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.
如果我使用 println 而不是 print,我希望看到 some_file.txt 以双倍行距打印出来。相反,程序在 some_file.txt 的每个字符后打印一个换行符。有人可以向我解释一下吗?我正在使用 Scala 2.8.0 Beta 1。
回答by Ben James
linesis a single string, not some iterable container of strings. This is because you called the .mkStringmethod on it.
lines是单个字符串,而不是一些可迭代的字符串容器。这是因为你调用了.mkString它的方法。
When you iterate over a string, you do so one character at a time. So the linein your foris not actually a line, it's a single character.
当您遍历一个字符串时,您一次只遍历一个字符。所以linein yourfor实际上不是一行,而是一个字符。
What you probably intended to do was call .getLinesinstead of .mkString
你可能打算做的是打电话.getLines而不是.mkString
回答by adamse
I suspect that for (line <- lines) print(line)doesn't put a line in linebut instead a character. Making the output as expected since the \nis there too. When you the replace the printwith printlnevery character gets its own line.
我怀疑这for (line <- lines) print(line)不会放一行,line而是放一个字符。由于\n也在那里,所以按预期输出。当您print用println每个字符替换时,会得到自己的一行。

