问题描述
所以我读到 App trait 有以下字段:
def delayInit(body: ⇒ Unit): Unitval executionStart: Longdef main(args: Array[String]): 单位
我知道如果一个特征只有一个方法,通过在类声明中的大括号之间放置代码",我将覆盖它.但在这里我有两种方法.那么为什么我会自动覆盖 main 而不是 delayInit?
您没有覆盖 main
方法.
由于 App
扩展了 DelayedInit
编译器像这样重写你的代码:
//之前:对象测试扩展应用{println("测试")}//后:对象测试扩展应用{delayInit{println("test")}}
来自 DelayedInit
文档:>
类和对象(但请注意,不是特征)继承了DelayedInit
标记特征将有它们的初始化代码改写如下:code
变成delayedInit(code)
.
App
trait 实现 delayedInit
像这样:
override def delayInit(body: => Unit) {initCode += (() => body)}
所以在 Test
对象构造函数代码 println("test")
被存储为函数 (() => Unit
) 在 initCode
字段.
App
的 main
方法被实现为对存储在 initCode
字段中的所有函数的调用:
for (proc
So I read that the App trait has the following fields:
def delayedInit(body: ⇒ Unit): Unit
val executionStart: Long
def main(args: Array[String]): Unit
I know that if a trait only has one method, by "putting code" between the curly braces in the class declaration I am overriding that. But here I have two methods. So why am I overriding automatically main and not delayedInit?
You are not overriding main
method.
Since App
extends DelayedInit
compiler rewrites your code like this:
// Before:
object Test extends App {
println("test")
}
// After:
object Test extends App {
delayedInit{println("test")}
}
From DelayedInit
documentation:
App
trait implements delayedInit
like this:
override def delayedInit(body: => Unit) {
initCode += (() => body)
}
So in Test
object constructor code println("test")
is stored as function (() => Unit
) in initCode
field.
main
method of App
is implemented as call for all functions stored in initCode
field:
for (proc <- initCode) proc()
这篇关于为什么如果我在 Scala 中扩展 App trait,我会覆盖 main 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!