Scala App val 在 main 方法中初始化
我有一些代码:
object Main extends App
{
val NameTemplate = """^([A-Za-z]+)_(\d+)\.png""".r
override def main (args:Array[String])
{
// Why is NameTemplate null here?
}
}
为什么 NameTemplate
未在主方法中初始化?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用
App
特征,则无需重写main
方法 - 只需在对象
主体中编写代码即可:它之所以有效,是因为
App
特征扩展了 DelayedInit 特征具有非常特殊的初始化过程。您甚至可以使用 args 访问参数,如示例所示。如果您不想扩展
App
,您仍然需要编写main
方法,但在这种情况下它将按预期工作: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:DelayedInit
特征(App
扩展)导致重写初始化代码以在特殊的delayedInit()
方法中执行。这通常会由main
调用。然而,由于您要覆盖main
,因此delayedInit()
代码永远不会被调用,因此您的值不会被初始化。正如 @tenshi 所解释的,您可以通过不扩展 App 或将主代码移动到 Main 对象的主体中来解决此问题。
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.