Programming  /  Scala August 17, 2010

Learning Scala part three – Executing Scala code

With Scala installed and some tools to work with it it’s about time to look at how we can execute Scala code. This is the third post in the Learning Scala series after all. Sorry to keep you waiting for so long before showing some code.

Anyhow, there are three ways to execute Scala code, interactively, as a script and as a compiled program. In this post we’ll take a quick look at each of them and print out the mandatory Hello world message.

Using the interactive interpreter

The easiest way to execute a single line of Scala code is to use the interactive interpreter with which statements and definitions are evaluated on the fly. We start the interactive interpreter using the Scala command line tool “scala” which is located in the bin folder in the folder where Scala is installed. With the proper environment variable in place you can just type “scala” to start it. Using the interactive interpreter we can do our first Hello world by using the println method.

C:\Users\Joel>scala
Welcome to Scala version 2.8.0.RC7 (Java HotSpot(TM) Client VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> println("Hello world")
Hello world

scala>

If a line of code that we type in to the interpreter doesn’t cause a console output the interpreter will print out the type and value of the statement.

scala> 1+1
res1: Int = 2

To quite the interpreter we type exit.

scala> exit

C:\Users\Joel>

 

Executing Scala code as a script

Another way to execute Scala code is to type it into a text file and save it with a name ending with “.scala”. We can then execute that code by typing “scala filename”. For instance, we can create a file named hello.scala with our Hello world in it:

// Inside hello.scala
println("Hello world!")

To execute it we specify the filename as a parameter to the Scala command line tool.

c:\learningscala>scala hello.scala
Hello world!

c:\learningscala>

In the above script we saw an example of a comment. Just like in Java and C# single line comments begin with two forward slashes (//). Comments that span several line begins with /* and ends with */.

Compiling Scala code

Finally, we can also execute Scala code by first compiling it using the scalac command line tool. Then the code will need to be executed in the context of an application so we’ll need to add an object with a main method.

object Greeting {
    def main(args: Array[String]) = println("Hello world!")
}

Wow, that’s more than a one line statement that writes to the console. We’ll discuss what this code does in a second. First, let’s look at how we can execute it though.

To compile it we type “scalac Greeting” which will produce two new files, Greeting$.class and Greeting.class.

c:\learningscala>scalac helloClass.scala

c:\learningscala>dir

Directory of c:\learningscala
Greeting$.class
Greeting.class
hello.scala
helloClass.scala

To execute the main method with it’s Hello world message we type “scala Greeting”.

c:\learningscala>scala Greeting
Hello world!

c:\learningscala>

The main method and the object construct

As you might have noticed that the last code example was very similar to how a console application looks in Java or C#. It had a method named main which accepted an array of strings as parameters. Just like in Java and C# a method named main serves as the entry point to the application.

However, you probably also saw that there were quite a few subtle differences. First of all we didn’t define the main method in a class but in an object and the method wasn’t marked as static. In fact the concept of static methods (or variables or classes) doesn’t exist in Scala. In Scala everything is an object. However Scala has an object construct with which we can declare singletons. In other word our main method is an instance method on a singleton object that is automatically instantiated for us.

Another thing to note is that the method signature looks a bit different. Let’s compare it with it’s Java (or C#) equivalent:

// Java/C#
public static void main(String[] args) //Body

// Scala    
def main(args: Array[String]) = //Body

We’ve already covered why it isn’t static. Another difference is that there’s no return type. In fact there is a return type, Unit which is similar to void, but it’s inferred by the compiler. Should we want to we can explicitly specify the return type by putting a colon and the type after the parameters:

def main(args: Array[String]) : Unit = //Body 

Another difference is of course that there’s no access level modifier (public in the Java version) in the Scala version. That’s because the default access level is public. Furthermore, the Scala version begins with a “def” keyword. As we don’t have to specify the return type and for methods without parameters we don’t even need to have the parenthesis we need to tell the compiler that this is a method somehow. Coming from Java or C# this might seem slightly awkward but it’s common in many other languages.

Recap and a look at the next part

In this part of the adventure to learn Scala we finally got to see some code. We learnt that there are three ways to execute Scala code, using the interactive interpreter, as a script and as a compiled application. In all of these cases we use the scala command line tool but in the last case we must first compile our code using the scalac command line tool.

In the next part we’ll look at how we create classes in Scala which is very similar to languages such as Java and C#. We’ll also take a pretty close look at constructors which works a bit differently in Scala.

About this post and the Learning Scala series

This post is a part of a series of posts in which I describe my experiences while trying to learn Scala. I try to do it in the form of a tutorial as I find doing so is an excellent way of consolidating knowledge and hopefully I can also help others. However, keep in mind that I’m in no way an expert on Scala. This is just a way to document what I’ve learned so far and there might be some things that I’ve misunderstood. If you’ve found such a thing and would like to help me correct that misunderstanding, or if you would like to leave any other kind of feedback don’t hesitate to leave a comment!

You can find links to all posts in this series at the bottom of the first post.

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

More about Scala