iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 2
1
Software Development

認識scala系列 第 2

Scala day 2 (Compile Scala)

Use scalac Compile Scala:

寫一隻 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

總結


  • 由於sacla是基於JVM上的語言,所以complie後還是會產生class檔,可在JVM執行.

參考資料


https://stackoverflow.com/questions/16821828/classnotfoundexceptionscala-predef-issue
https://stackoverflow.com/questions/30731414/why-there-are-two-class-files-generated-after-compiling-scala-code


上一篇
Scala day 1 (Run scala)
下一篇
Scala day 3 (Define something)
系列文
認識scala30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言