2011-09-02 153 views
13

根據this,Scala方法屬於一個類。但是,如果我在REPL中定義了一個方法,或者在我使用scala執行的腳本中定義了一個方法,那麼該方法屬於哪個類?Scala:如果沒有定義類,是否有默認類?

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

scala> hoho("rahul") 
hoho rahul 

在這個例子中,沒有方法屬於什麼階級?

回答

17

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)顯示代碼被包裝在對象Mainmain(args:Array[String])中的代碼塊中。您可以訪問參數argsargv

+0

謝謝。如果我要將方法定義保存在.scala腳本中並使用scala執行它,是否也會發生同樣的情況? – Rahul

+0

@Rahul,我已經添加了腳本的信息,機制是不同的。 – huynhjl

相關問題