Reputation: 1765
I have this very simple code (scala-2.10):
import scala.io.Source
object Test2 {
def main(args: Array[String]): Unit = {
for(line <- Source.fromFile("/Users/alexei/words.txt", "utf-8").getLines()) {
println(line)
}
}
}
I get this error message when compiling:
Test2.scala:3: error: ';' expected but 'object' found.
object Test2 {
^
one error found
I am terribly confused when to use semicolons or not. I have other code similar to this and it has no issues compiling without any semicolons what so ever.
Can someone please explain this specific error and detail all the situations where a semicolon is needed?
Upvotes: 1
Views: 2880
Reputation: 39577
The compiler happens to take LF or FF for purposes of EOL and semicolon inference (which is really nl
inference).
It ignores the CR in a CR-LF sequence.
This works:
import scala.io.Source^Lobject Test
There have been a few related questions about line endings in Scala, which is too bad, because it feels like the Dark Ages. You can talk to your phone but Scala can't figure out my source file encoding?
For vim see Command line option to open mac formatted file in Vim
Odersky was an emacs guy, so maybe that's why it doesn't do full-spectrum line-ending detection.
Upvotes: 1
Reputation: 1765
My editor's line endings are messed up in Sublime Text 3 for some reason. I opened up the file in vim and the entire file was represented as one line(^M as new line characters).
I had to run the following in Vim to fix the line endings
:%s/\r/\r/g
This means that according to dhg's answer above the statements need to be separated by a semicolon.
Because I thought the statements were on their own separate lines I did not place any semicolons and that is where my error is coming from.
Thanks to senia for pointing out that possibility.
Upvotes: 1
Reputation: 41858
You may want to bookmark this
http://jittakal.blogspot.com/2012/07/scala-rules-of-semicolon-inference.html
I don't see why it is complaining as your object line is the start of a line, isn't within a parentheses and the previous line was complete
Sometimes the compiler may get confused and you need to group with parenthesis but I don't see that here.
Upvotes: 1
Reputation: 52681
The code works just fine for me.
The only time you need semicolons is when you are writing multiple statements on the same line. Otherwise the line-break indicates the separation. So you don't need any semicolons in your current code, but if you would if you wanted to do this:
println(line); println(line)
Instead of just
println(line)
println(line)
Upvotes: 5