REPL將所有語句(實際上會重寫您的語句)自動包裝在對象中。你可以看到它在行動,如果你使用-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))
}
}
}
}
所以你的方法hoho
真的$line1.$read.$iw.$iw.hoho
。然後,當您稍後使用hoho("foo")
時,它將重寫以添加包和外部對象。
其他注意事項:對於腳本,-Xprint:typer
(-Xprint:parser
)顯示代碼被包裝在對象Main
的main(args:Array[String])
中的代碼塊中。您可以訪問參數args
或argv
。
謝謝。如果我要將方法定義保存在.scala腳本中並使用scala執行它,是否也會發生同樣的情況? – Rahul
@Rahul,我已經添加了腳本的信息,機制是不同的。 – huynhjl