Scala println in a for loop
Asked Answered
D

2

6

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.

Degrade answered 14/3, 2010 at 11:43 Comment(0)
D
23

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 your for is not actually a line, it's a single character.

What you probably intended to do was call .getLines instead of .mkString

Diphthongize answered 14/3, 2010 at 11:49 Comment(1)
He called .mkString on the result of fromPath, which is an Iterator[Char] with some added stuff. I know you know this, but I think you could make it clearer. You could also put an example of a for comprehension over a String literal.Watcher
L
2

I suspect that for (line <- lines) print(line) doesn't put a line in line but instead a character. Making the output as expected since the \n is there too. When you the replace the print with println every character gets its own line.

Lenient answered 14/3, 2010 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.