During scala training, I came across the following weird 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 the compiler to throw an error on val 2 = 123 , because identifiers should not start with a number, but the code compiles without warning. However, at runtime, it throws an exception immediately:
An exception is thrown in the main thread java.lang.ExceptionInInitializerError at temptests.TempTest.main (TempTest.scala) in sun.reflect.NativeMethodAccessorImpl.invoke0 (native method) in sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethplod.Implj.Iml sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) in java.lang.reflect.Method.invoke (Method.java:498) in com.intellij.rt.execution.application.AppMain.main (AppMain.java: 144) Called: scala.MatchError: 123 (class java.lang.Integer) in temptests.TempTest $. (TempTest.scala: 5) at temptests.TempTest $. (TempTest.scala) ... 6 more
I'm just wondering: how is val 2 = 123 understood by scala ? Why is there no compile-time error?
scala runtime-error
cubic lettuce
source share