APPENDIX C: Introduction to Scala 425
Note The semicolon at the end of a statement is usually optional.
Line 1: The main() method is defined in an object, not in a class. Scala has an
object construct with which you can declare a singleton object. You will learn
more about singletons later in this appendix.
Line 2: Scala program processing starts from the main() method, which is a
mandatory part of every Scala program. The main() method is not marked
as static. In Scala, everything is an object. The main() method is an instance
method on a singleton object that is automatically instantiated.
Line 2: There is no return type. Actually, there is Unit, which is similar to void,
but it is inferred by the compiler. You can explicitly specify the return type by
putting a colon and the type after the parameters.
def main(args: Array[String]) : Unit = {
}
Line 2: There is no access-level modifier in Scala. You have a public modifier in
Java in this context, but Scala does not specify the public modifier because the
default access level is public.
Line 2: Scala uses the def keyword to tell the compiler that this is a method.
Save the code in Listing C-1 in a file called HelloWorld.scala and compile the code using the
following command:
scalac HelloWorld.scala
Now run the program using this command:
scala HelloWorld
Hello, World!
Note Java requires you to put a public class in a file named after the class. For example, you should put
class HelloWorld in file HelloWorld.java. In Scala, you can name .scala files anything you want, no
matter what Scala classes or code you put in them. However, it is recommended you name files after the
classes they contain as is done in Java so as to easily locate classes based on file names.