简体   繁体   English

Scala:如果未定义任何类,是否有默认类?

[英]Scala: Is there a default class if no class is defined?

According to this , Scala methods belong to a class. 根据 ,Scala的方法属于一类。 However, if I define a method in REPL or in a script that I then execute using scala, what class does the method belong to ? 但是,如果我在REPL或脚本中定义了一个方法,然后使用Scala执行该方法,则该方法属于哪个类?

scala> def hoho(str:String) = {println("hoho " + str)}
hoho: (str: String)Unit

scala> hoho("rahul")
hoho rahul

In this example, what class does the method belong to ? 在此示例中,该方法属于哪个类?

The REPL wraps all your statements (actually rewrites your statements) in objects automagically. REPL自动将所有语句包装在对象中(实际上是重写您的语句)。 You can see it in action if you print the intermediate code by using the -Xprint:typer option: 如果使用-Xprint:typer选项打印中间代码,则可以看到它的作用:

scala> def hoho(str:String) = {println("hoho " + str)}
[[syntax trees at end of typer]]// Scala source: <console>
package $line1 {
  final object $read extends java.lang.Object with ScalaObject {
    def this(): object $line1.$read = {
      $read.super.this();
      ()
    };
    final object $iw extends java.lang.Object with ScalaObject {
      def this(): object $line1.$read.$iw = {
        $iw.super.this();
        ()
      };
      final object $iw extends java.lang.Object with ScalaObject {
        def this(): object $line1.$read.$iw.$iw = {
          $iw.super.this();
          ()
        };
        def hoho(str: String): Unit = scala.this.Predef.println("hoho ".+(str))
      }
    }
  }
}

So your method hoho is really $line1.$read.$iw.$iw.hoho . 因此,您的方法hoho实际上是$line1.$read.$iw.$iw.hoho Then when you use hoho("foo") later on, it'll rewrite to add the package and outer objects. 然后,当您稍后使用hoho("foo")时,它将重写以添加包和外部对象。

Additional notes: for scripts, -Xprint:typer ( -Xprint:parser ) reveals that the code is wrapped inside a code block in the main(args:Array[String]) of an object Main . 附加说明:对于脚本, -Xprint:typer-Xprint:parser )显示代码被包装在对象Mainmain(args:Array[String])中的代码块内。 You have access to the arguments as args or argv . 您可以以argsargv访问参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM