为什么如果我在 Scala 中扩展 App trait,我会覆盖 main 方法? [英] Why if I extend the App trait in Scala, I override the main method?

查看:41
本文介绍了为什么如果我在 Scala 中扩展 App trait,我会覆盖 main 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我读到 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 <- initCode) 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:

Classes and objects (but note, not traits) inheriting the DelayedInit marker trait will have their initialization code rewritten as follows: code becomes delayedInit(code).

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 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆