How to create Scala script
Hello World
Create HelloWorld.scala
file with the following
object HelloWorld extends App {
println("Hello World")
}
Compile it by
scalac HelloWorld.scala
Run it with:
scala HelloWorld
Read arguments
Once you have create an object that extends App
, you can access arguments’ array with args
.
object HelloWorld extends App {
if (args.length == 0) {
println("Hello World")
} else {
println("Hello " + args(0))
}
}
Run it
scalac HelloWorld.scala
scala HelloWorld
What if I do not want to extend App?
Then you can implement main
method
object HelloWorld {
def main(args: Array[String]) = {
println("Hello " + args(0))
}
}
Script
You can also create script hello.sh
#!/usr/bin/env scala
println("Hello World")
Then you can simply run it with
chmod +x hello.sh
hello.sh
Updated 2018-07-30