Scala 对象没有扩展

Scala object extends nothing

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

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

Hello World

谁能给我解释一下,这里发生了什么?
Main class 是否在此处扩展匿名 class/trait

它脱糖成

object Main extends Object

您可以通过 scalac -print 编译来检查这一点。

Grammar

ClassTemplateOpt  ::=  ‘extends’ ClassTemplate | [[‘extends’] TemplateBody]

哪里

TemplateBody      ::=  [nl] ‘{’ [SelfType] TemplateStat {semi TemplateStat} ‘}’

据我所知,如果我们检查 [[‘extends’] TemplateBody],它似乎确实被指定为有效。

如果我们使用 scala -Xprint:typer 反编译代码,我们会看到 Main extends 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 下的 object/class 定义中:

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