gpt4 book ai didi

Scala 对象不扩展任何内容

转载 作者:行者123 更新时间:2023-12-04 17:14:32 25 4
gpt4 key购买 nike

我在我们的代码库中遇到了一段代码,在我看来无效,但编译成功并运行。

object Main extends {
def main(args: Array[String]): Unit = {
print("Hello World")
}
}

Hello World



有人可以解释一下,这里发生了什么?
是否 Main类在这里扩展匿名 class/ trait ?

最佳答案

如果我们使用 scala -Xprint:typer 反编译代码,我们看到 Main扩展 AnyRef :

scalac -Xprint:typer Main.scala                                                                                               
[[syntax trees at end of typer]] // Main.scala
package com.yuvalitzchakov {
object Main extends scala.AnyRef {
def <init>(): com.yuvalitzchakov.Main.type = {
Main.super.<init>();
()
};
def main(args: Array[String]): Unit = scala.Predef.print("Hello World")
}
}

这也记录在 Scala specification 中。在对象/类定义下:

An object definition defines a single object of a new class. Its most general form is object m
extends t
. Here, m is the name of the object to be defined, and t is a template of the form

sc with mt1 with … with mtn { stats } which defines the base classes, behavior and initial state of m. The extends clause extends sc with
mt1 with … with mtn
can be omitted, in which case extends scala.AnyRef is assumed.



此语法也适用于 early initializers :
abstract class X {
val name: String
val size = name.size
}

class Y extends {
val name = "class Y"
} with X

关于Scala 对象不扩展任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com