There is a lot of documentation on http://scala.epfl.ch/docu/index.html, including the specification, the rationale, and “Scala by Example”, which includes a number of code examples.
Here’s an extremely simple Scala <i>script</i> (not a full-fledged program):
import javax.swing._;
object HelloWorld extends JFrame( "Greetings" ) {
def main( args: Array[String] ) {
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
add( new JLabel( "Hello World" ) )
pack()
setVisible( true )
}
}
HelloWorld.main(null)
Copy it into a file called “Hello.scala”, and on the command line, run “scala Hello.scala”. You’ll get a small Swing window appearing.
A few other things to note:
Of course, a simpler script to achieve the same result (but which doesn’t show quite as much of Scala) is just this:
import javax.swing._ val frame = new JFrame( "Greetings" ) frame.add( new JLabel( "Hello World" ) ) frame.pack() frame.setVisible( true )
which even works in the REPL (You do need to remove the call to set the default close operation to EXIT_ON_CLOSE, so the REPL doesn’t exit too.)
Scala procedures, functions, and methods are all introduced with the def keyword. Procedures and methods that don’t return a value (technically, they actually return an object of type Unit, similar to void in Java except that it’s an object like any other) look like this:
def procName(paramName1: type1, paramName2: type2, . . .) {
...body...
}
or
def procName(paramName1: type1, paramName2: type2, . . .):Unit = {
...body...
}
Functions and methods that do return a value are defined in a similar way:
def funName(paramName1: type1, paramName2: type2, . . .) : returnType = {
...body...
}
Finally, as you may have guessed by the fact that we refer to procedures and functions as well as to methods: Scala allows procedures and functions that are not part of a class definition. Very nice!
These are all different types of “class level” OO concepts.
Classes define types and provide a template for object creation and initialization.
TODO
Traits are composable units of behaviour, a class can extend multiple traits. Traits do not have constructors and are similar to Java’s abstract classes (in content) and Java´s interfaces (in usage). They are implemented via “mix-in” composition.
TODO
Objects are instances of classes and are created at runtime.
TODO
Companion objects are the module (static part) associated with a class.
TODO
Case classes are a special type of class suited to structural pattern matching. They implicitly define a factory method with the name of the class, implicitly get a val prefix on parameters (constructor params become object constants) and proper redefinitions of: toString, hashCode, and equals methods.
TODO
Enumerations are lighter that (case) classes and similar to Java´s enum
//Definition
object enumName extends Enumeration {
val v1, v2, v3, . . . = Value
}
//Usage
val d: enumName.Value //type
d = enumName.v1 //values