Scala - semicolon inconsistency

牧云@^-^@ 提交于 2020-01-05 20:22:39

问题


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?


回答1:


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)



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/21355908/scala-semicolon-inconsistency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!