Compiling Scala

You want to compile the code explicitly if you have multiple files or want to distribute the bytecode instead of the source code. Here’s how to write a piece of Scala code and compile it using the scalac compiler. In the following example, we define a small executable code in an object named Sample that extends the App trait—you’ll soon learn about Scala singleton objects and traits. App instructs the compiler to generate the necessary main method to make Sample the starting class.

FirstStep/Sample.scala
 
object​ Sample ​extends​ App {
 
println(​"Hello Scala"​)
 
}

Compile the code with the command scalac Sample.scala, and then run it using either the scala tool or the java command. To use the scala tool, type scala Sample. To use the java tool, specify the classpath for scala-library.jar. Here’s an example of compiling with the scalac tool and running the program first with the scala tool and then with the java tool on my Mac:

 
> scalac Sample.scala
 
> scala Sample
 
Hello Scala
 
> java -classpath /opt/scala/current/lib/scala-library.jar:. Sample
 
Hello Scala

Here’s a small trick: name current as a symbolic link to the current version of Scala installed on your machine. The symbolic link will help switch Scala versions easily without having to change the PATH and classpath settings. To change versions, simply change the symbolic link. You could create a similar symbolic link on your machine, or you could replace the word current with the appropriate directory name for the current version of Scala you’re using.

On Windows, we’d set the classpath to the full path of the scala-library.jar file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.172.195