新类Scala中的“自我”是什么意思

Cam*_*iao 1 scala self apache-spark

最近我正在阅读火花的来源。当到达“org.apache.spark.deploy.SparkSubmit”类时,我对关键字“self”和运算符“=>”感到困惑。有没有人可以为我解释一下?

override def main(args: Array[String]): Unit = {
val submit = new SparkSubmit() {
  self =>

  override protected def parseArguments(args: Array[String]): SparkSubmitArguments = {
    new SparkSubmitArguments(args) {
      override protected def logInfo(msg: => String): Unit = self.logInfo(msg)

      override protected def logWarning(msg: => String): Unit = self.logWarning(msg)
    }
  }

  override protected def logInfo(msg: => String): Unit = printMessage(msg)

  override protected def logWarning(msg: => String): Unit = printMessage(s"Warning: $msg")

  override def doSubmit(args: Array[String]): Unit = {
    try {
      super.doSubmit(args)
    } catch {
      case e: SparkUserAppException =>
        exitFn(e.exitCode)
      case e: SparkException =>
        printErrorAndExit(e.getMessage())
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

BTW:这个问题和“重复的问题”完全不同。尽管这两个非常相似,但我要问的是“新类”关键字附近的“self =>”,而不是scala的类定义中带有“某个名称=>”的“重复”。这不是同一个问题

Tim*_*Tim 7

该声明

self =>
Run Code Online (Sandbox Code Playgroud)

被称为“自类型注释”,它创建一个名为的值self,该值引用正在构造的类的实例。这可以用于this类的值不可用的地方。特别是,它可以在嵌套类中使用,其中this引用嵌套类,而对外部类的引用不会自动可用。

在你的情况下,self在这里使用:

new SparkSubmitArguments(args) {
  override protected def logInfo(msg: => String): Unit = self.logInfo(msg)

  override protected def logWarning(msg: => String): Unit = self.logWarning(msg)
}
Run Code Online (Sandbox Code Playgroud)

这使得SparkSubmitArguments使用来自外部包含类的logInfologWaringing方法的新实例。您不能this在代码的这一点使用,因为它会引用内部类,而不是外部类。(如果你在this这里使用,你会得到一个无限循环)


Dim*_*ima 5

它是 的别名this。这样做是为了消除内部类中自引用的歧义。

当您this在内部类的范围内使用时,它指的是内部类的实例。如果您需要对外部类的引用,则需要一个别名:

  class Foo { self => 
    val x = 1
    new AnyRef { 
      val x = 2
      println(this.x) // 2
      println(self.x) // 1
    }
  }
Run Code Online (Sandbox Code Playgroud)