I am a newbie to Scala, it\'s the first time I\'m running Scala, when I installed Scala, I created a file named Hello.scala
, the content is:
pr
Adding -nc
flag saved my day.
scala -nc Hello.scala
What is -nc
?
-nc no compilation daemon: do not use the fsc offline compiler
Source: http://alvinalexander.com/java/jwarehouse/scala-2.11/compiler/scala/tools/nsc/GenericRunnerCommand.scala.shtml
What is fsc offline compiler
?
fsc – Fast offline compiler for the Scala 2 language
Source: http://www.scala-lang.org/old/sites/default/files/linuxsoft_archives/docu/files/tools/fsc.html
If you’re on some flavor of Unix, you can run a Scala script as a shell script by prepending a pound bang directive at the top of the file.
For example, type the following into a file named helloarg
:
#!/bin/sh
exec scala "$0" "$@"
!#
// Say hello to the first argument
println("Hello, "+ args(0) +"!")
The initial #!/bin/sh
must be the very first line in the file.
Once you set its execute permission:
$ chmod +x helloarg
You can run the Scala script as a shell script by simply saying:
$ ./helloarg globe
If you’re on Windows, you can achieve the same effect by naming the
file helloarg.bat
and placing this at the top of your script:
::#!
@echo off
call scala % 0 % *
goto :eof
::!#
This works in mac for development.
#!/usr/bin/env scala -nc
println("hello");
Just a summary of what I know. I used to be confused by how to run a scala file properly.
In sum, we got 3 ways to achieve this:
For script files. For script, it means it's just as the same as you type lines of statements in the REPL, or use :paste
mode to paste multiple lines. Something like:
println("foo")
Compile an object containing main method with scalac
. You can extends
App trait to easily implement.
def main(args: Array[String]) : Unit
You may say "You liar, there are just two ways". But for the second one, I think there's too ways to get it running.
scala -howtorun:object ObjectName -cp "./"
: The -cp
is just for insurance.java -cp "/path/to/your/scala-jars" ObjectName
: So the difference is just the classpath need to be included.Write the println
statement inside the main function:
object HelloWorld {
def main(args: Array[String]) {
println("Hello World!")
}
}
Then execute: scala -nc HelloWorld.scala
When you are trying to run scala follow below steps:
scala <filename.scala><Input if any>
from cmd promptbelow is the example:
scala /home/prakash/Desktop/babyname.scala < /home/prakash/Desktop/ND
Note: above command must be typed in unix cmd prompt not in scala repl.