I have some code:
object Main extends App
{
val NameTemplate = """^([A-Za-z]+)_(\d+)\.png""".r
override def main (args:Array[String])
{
// Why is NameTemplate null here?
}
}
Why is NameTemplate
not initialized within the main method?
If you are using
App
trait, then you don't need to overridemain
method - just write your code in the body of theobject
:It works because
App
trait extends DelayedInit trait which has very special initialization procedure. You can even access arguments withargs
, as shown in the example.You still need to write
main
method if you don't want to extendApp
, but in this case it will work as expected:The
DelayedInit
trait (whichApp
extends) causes rewriting of intialisation code to execute within a specialdelayedInit()
method. This would then normally be invoked bymain
. Since you are overridingmain
, however, thedelayedInit()
code is never being invoked, and as such your value is not being initialised.As @tenshi explains, you can get around this either by not extending
App
or by moving your main code into the body of yourMain
object.