Scala gives no compile-time error when assigning a value to a number literal?

Viewed 495

While learning scala I stumbled upon the following strange snippet:

package temptests

object TempTest {
  //def 2 = 123 // does not compile
  val 2 = 123 // compiles, but leads to an exception at runtime

  def main(args: Array[String]) = { // just do something to load this class
    println("Hello")
  }
}

I would expect that the compiler would throw an error on val 2 = 123 because identifiers must not start with a digit, but the code compiles without a warning. However, at runtime it immediately throws an Exception:

Exception in thread "main" java.lang.ExceptionInInitializerError at temptests.TempTest.main(TempTest.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Caused by: scala.MatchError: 123 (of class java.lang.Integer) at temptests.TempTest$.(TempTest.scala:5) at temptests.TempTest$.(TempTest.scala) ... 6 more

I am just curious: how is val 2 = 123 understood by Scala? Why is there no compile-time error?

2 Answers
Related