toString on a negative number doesn't compile in Scala Worksheet

跟風遠走 提交于 2019-12-23 10:19:10

问题


If I create a Scala Worksheet in Eclipse as follows:

object negative {

  2.toString                                //> res0: String = 2

  (2).toString                              //> res1: String = 2

  // compile error
  (-2).toString
}

the final line causes a compile error:

';' expected but ')' found. illegal start of simple expression

However, the same three lines compile and run fine within a normal Scala source file.

Why does this not work in the worksheet?

This is using Eclipse 3.7.2, Scala IDE 3.0.0.v-2_10, Scala Worksheet 0.1.4.v-2_10

[Updated: this question originally used toBinaryString, but the problem occurs even with toString, so I have simplified it]


回答1:


It is a bug. The code in the main object (the first one) of a worksheet is instrumented before being executed. In the 2 mentioned case, the result of the instrumentation is not valid Scala code.

But it is only a problem if the code is at the top level in the main object. If the code is moved to a function or a different object in the same file, it works fine.




回答2:


Eclipse worksheets are quite beta; for example last I checked, it couldn't handle a @tailrec decoration on a function.

So this is most probably a bug or limitation in Eclipse. After all, the feature seems quite new, and there are many other bugs.




回答3:


(-2).toBinaryString gives same error for me.

Note that java.lang.Integer.toBinaryString(-2)works just fine.



来源:https://stackoverflow.com/questions/18961790/tostring-on-a-negative-number-doesnt-compile-in-scala-worksheet

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