Scala:如果没有定义类,是否有默认类? [英] Scala: Is there a default class if no class is defined?

查看:31
本文介绍了Scala:如果没有定义类,是否有默认类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据this,Scala方法属于一个类.但是,如果我在 REPL 或脚本中定义了一个方法,然后我使用 scala 执行该方法,那么该方法属于哪个类?

According to this, Scala methods belong to a class. 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 ?

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 ?

推荐答案

REPL 自动将您的所有语句(实际上是重写您的语句)包装在对象中.如果您使用 -Xprint:typer 选项打印中间代码,您可以看到它的作用:

The REPL wraps all your statements (actually rewrites your statements) in objects automagically. You can see it in action if you print the intermediate code by using the -Xprint:typer option:

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))
      }
    }
  }
}

所以你的方法hoho实际上是$line1.$read.$iw.$iw.hoho.然后当您稍后使用 hoho("foo") 时,它将重写以添加包和外部对象.

So your method hoho is really $line1.$read.$iw.$iw.hoho. Then when you use hoho("foo") later on, it'll rewrite to add the package and outer objects.

附加说明:对于脚本,-Xprint:typer (-Xprint:parser) 表明代码被包裹在 main(args:Array[String]) 对象 Main.您可以以 argsargv 的形式访问参数.

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. You have access to the arguments as args or argv.

这篇关于Scala:如果没有定义类,是否有默认类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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