寫一隻 HelloWorld.scala
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello World!")
}
}
使用 scalac compile scala 程式,會出現可以在JVM執行的class檔.
daniel@Danielde-MacBook-Pro > scalac HelloWorld.scala
daniel@Danielde-MacBook-Pro > ll
-rwxrwxrwx 1 daniel staff 670B 11 29 00:01 HelloWorld$.class
-rwxrwxrwx 1 daniel staff 608B 11 29 00:01 HelloWorld.class
-rwxrwxrwx 1 daniel staff 97B 11 22 22:21 HelloWorld.scala
執行java HelloWorld,卻出現錯誤.
daniel@Danielde-MacBook-Pro > java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: scala/Predef$
at HelloWorld$.main(HelloWorld.scala:4)
at HelloWorld.main(HelloWorld.scala)
Caused by: java.lang.ClassNotFoundException: scala.Predef$
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
上網查了一下說是少了scala-library.jar,所以改成這樣執行:
daniel@Danielde-MacBook-Pro > java -cp "scala-2.12.4/lib/scala-library.jar:." HelloWorld
Hello World!
執行成功~因為沒有設classpath=. (當前目錄),所以-cp時要自己加.
另外上面的例子 compiler 後會產生兩個.class 檔的原因是因為 HelloWorld.scala 是 objcet 的關係.object HelloWorld 會轉成 HelloWorld$.class,但由於 sacala 的 object 都是 singleton 的,在 JVM 裡類似 static 的物件,所以會產生一個 HelloWorld.class 裡面放的都是 static 一些成員.
如果是 class 的話只會產生一個class檔.寫一隻 Student class :
class Student {
val id = ""
val name = ""
}
然後再 compiler 看看,就只會產生一個 class 檔了 :
daniel@Danielde-MacBook-Pro > ll
total 1536
-rwxrwxrwx 1 daniel staff 46B 12 5 11:39 Student.scala
daniel@Danielde-MacBook-Pro > scalac Student.scala
daniel@Danielde-MacBook-Pro > ll
total 1792
-rwxrwxrwx 1 daniel staff 857B 12 5 11:41 Student.class
-rwxrwxrwx 1 daniel staff 46B 12 5 11:39 Student.scala
https://stackoverflow.com/questions/16821828/classnotfoundexceptionscala-predef-issue
https://stackoverflow.com/questions/30731414/why-there-are-two-class-files-generated-after-compiling-scala-code