trait Application
extends AnyRef

The Application trait can be used to quickly turn objects into executable programs, but is not recommended. Here is an example:

  object Main extends Application {
Console.println("Hello World!")

Here, object Main inherits the main method of Application. The body of the Main object defines the main program. This technique does not work if the main program depends on command-line arguments (which are not accessible with the technique presented here).

It is possible to time the execution of objects that inherit from class Application by setting the global scala.time property. Here is an example for benchmarking object Main:

  java -Dscala.time Main

In practice the Application trait has a number of serious pitfalls:

  • As described above, there is no way to obtain the command-line arguments because all code in body of an object extending Application is run as part of the static initialization which occurs before Application's main method even begins execution.
  • Threaded code that references the object will block until static initialization is complete. However, because the entire execution of an object extending Application takes place during static initialization, concurrent code will always deadlock if it must synchronize with the enclosing object.
  • Static initializers are run only once during program execution, and JVM authors usually assume their execution to be relatively short. Therefore, certain JVM configurations may become confused, or simply fail to optimize or JIT the code in the body of an object extending Application. This can lead to a significant performance degradation.



  1. trait Application 可以讓您便捷的來執行程式, 但這是不被推驚的.
  2. trait Application 使該物件繼承其 main(), 其程式內容即為main程序, 但這技術無法給予從命令列傳遞的參數.


使用這個特質的方法是,首先在你的單例對像名後面寫上「extends Application」 。然後代之以main方法,你可以把想要放在main方法裡的代碼直接放在單例對象的大括號之間。就這麼簡單。之後可以像對其它程序那樣編譯和運行。

這種方式之所以能奏效是因為特質Application聲明了帶有合適的簽名的main方法,並由你的單例對像繼承,使它可以像個Scala程序那樣用。 大括號之間的代碼被收集進了單例對象的主構造器:primary constructor,並在類被初始化時被執行。如果你不明白所有這些指的是什麼也不用著急。之後的章節會解釋這些,目前可以暫時不求甚解。

繼承自Application比寫個顯式的main方法要短,不過它也有些缺點。首先,如果想訪問命令行參數的話就不能用它,因為args數組不可訪問。 比如,因為Summer程序使用了命令行參數,所以它必須帶有顯式的main方法。第二,因為某些JVM線程模型裡的局限,如果你的程序是多線程的就需要 顯式的main方法。最後,某些JVM的實現沒有優化被Application特質執行的對象的初始化代碼。因此只有當你的程序相對簡單和單線程情況下你 才可以繼承Application特質。