Wikipedia's canonical Hello World examples in Scala. Two ways of doing the same thing -
object HelloWorld extends Application { println("Hello, world!") }
object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } }
[greg:~] cd dev/src [greg:src] mkdir scala [greg:src] cd scala [greg:scala] mkdir firstProject [greg:scala] cd firstProject [greg:firstProject] alias scala=/opt/scala-2.7.5.final/bin/scala [greg:firstProject] alias scalac=/opt/scala-2.7.5.final/bin/scalac [greg:firstProject] scalac HelloScala.scala [greg:firstProject] scala -classpath .: HelloScala Hello, world! [greg:firstProject]
Although I added /opt/scala-2.7.5.final/bin to the system PATH variable in ~/.bash_profile, in order to invoke the compiler and the runtime, I found it necessary to alias the two scripts (see above).
Scala is described as a multi-paradigm language. It has the features of an object-oriented language and a functional language. Venkat Subramaniam shows how to run Scala code as Unix scripts by use of what is called the "sha-bang" (the #! ... !# portion of the text below) which is a command to the command line interpreter telling it that the script is to be run by the program named in the "sha-bang".
#!/usr/bin/env scala !# println("Hello," + args(0))
If I save the above code in script.scala I can run it without directly invoking Scala:
[greg:firstProject] script.scala Greg Hello,Greg [greg:firstProject]
Other Features of Scala
Scala allows you to define nested packages just like C++ and C# namespaces. You may define many packages and classes in one source file.Scala's default access level is public. Scala's protected access is more restrictive than Java's, giving access only to derived classes. At the Package level, control is more granular than Java's.
Combining Functional and Object Oriented Paradigms
package Cars { package Sport { class Porsche { def go() = 100 } } package Economy { class Corolla { def go() = 50 } } } object Car { def main(args: Array[String]) { val car1 = new Cars.Sport.Porsche(); val car2 = new Cars.Economy.Corolla(); println(car1.go()) println(car2.go()) } }
[greg:firstProject] scalac Cars.scala [greg:firstProject] ls -l total 56 -rw-r--r-- 1 greghelton staff 1030 Jul 26 22:03 Car$.class -rw-r--r-- 1 greghelton staff 566 Jul 26 22:03 Car.class drwxr-xr-x 4 greghelton staff 136 Jul 26 22:03 Cars -rw-r--r--@ 1 greghelton staff 316 Jul 26 21:59 Cars.scala [greg:firstProject] ls cars Economy Sport [greg:firstProject] ls Cars/Sport Porsche.class [greg:firstProject] ls Cars/Economy Corolla.class [greg:firstProject] scala Car 100 50 [greg:firstProject]