Advertisement
  1. Code
  2. Scala
Code

From Zero to Hello World in Scala

by
Length:LongLanguages:

Scala is one of the most attractive programming languages out right now. There is a lot of hype around it and programmers world-wide are publicly recognizing it as the possible next big thing in programming. Here's why. Scala is all about functional programming in an object oriented context. It tries to take the best of both worlds and combine them into a highly efficient, intelligent, and relatively easy to understand language. Right now it is the leader in today's renaissance of functional programming languages.

I recently finished Martin Odersky's Scala course and I found it very difficult to figure out how to get started. You know, that first step when you want to start coding, but you don't know what tools are at your disposal, what IDE to use, or which unit testing framework to choose. This tutorial will be about you, the newcomer to Scala, preparing your development environment so you can get started more easily.


The Pieces of the Puzzle

Here are the puzzle pieces we'll talk about in this lesson, feel free to skip over the ones you already know:

  • Simple Build Tools (SBT) - this is the tool that generates projects, dependencies, etc. for Scala
  • NetBeans with Scala Plugins - how to integrate Scala with NetBeans
  • Hello World - we'll create our first Scala source file
  • Scalatest - the recommended unit testing framework for Scala

We'll take each topic on the list and discuss it at a beginner level and finally we'll see how all of these pieces work together.


Software Requirements

Before you begin, ensure that you have the latest Java SDK installed on your computer. Since Scala runs on the Java Virtual Machine (JVM), the SDK is required. The rest of the topics on our list may require the Java SDK, either directly or indirectly, so it's good to have.

You do not need to have Scala itself installed. We'll talk about this in the next chapter.


Scala's Simple Build Tools (SBT)

If you're a PHP developer, then you are probably familiar with Composer. If you're a Ruby guru, you know and love Bundler. If you program in some other language, I am sure there is a package manager for that, too.

SBT is similar to the above package managers, but, while Composer requires you to have PHP preinstalled in the same way as Bundler needs Ruby, Scala does not need to be installed on the system before you can use SBT. In fact, the specific Scala version you want to use for your project can simply be specified as a dependency in SBT. You may wonder how this is possible. As I mentioned before, Scala runs on the JVM; basically, it's just a Java library. The packages for Scala may also be simple .jar files. So, SBT, itself, is just a Java program. You only need Java, which you probably already have anyway.

There are many different ways you can approach installing SBT. For cross-platform reasons between Linux, Mac, and Windows, my preferred way to install SBT is just to take the archive, put it in a directory, extract it into my home directory, and add its path to the system.

A Platform Independent Way to Install SBT

Download the latest stable SBT from the official repository. Look for a folder without a "Beta" or "R" or "M" at the end. That will be the stable version. At the moment of writing this tutorial the latest stable version is 0.12.3.

The archive contains an sbt directory inside of it. Just extract this into your favorite location. I prefer it to be somewhere in my home directory like /home/csaba/Programming/Scala/sbt

Next, add the path to your SBT bin directory, to your PATH variable. On UNIX-like systems, if you use Bash, add a line like this to your ~/.bash_profile or ~/.bashrc file:

The $HOME variable usually points to your home directory. You can reuse it in your configuration files. Windows users may have a different variable for this. Don't forget the export command on the second line, otherwise your PATH variable will only be available inside the configuration file.

Now, test that your SBT installation was successful. Open a console or command line tool and type:

The $ sign is the Bash prompt, the rest is the command that you'll enter. As you can see, I have version 0.12.2 installed.

For other ways to install SBT, you can check the official setup documentation.

Creating a New Project

Create a folder where you want your future code to be, open a console, change into the newly created directory, and simply run the command sbt.

Note that the current project was set to the folder you are in and that your console has changed. You are now inside the SBT console. You can leave this console by pressing CTRL+d or CTRL+c or by issuing the command exit.

In this console, you can tell SBT to do a lot of things. Just press TAB twice and confirm with y to see the complete list of available commands.

Project Based Build Configuration

Using the system wide or user wide settings for all of your projects may not be the best option. Each project is different, it needs different dependencies, has a different name and so on. To tell SBT about information like this we have to create a file called build.sbt. It must be placed into the project's root folder, which you can find on the last line, in the previous example.

The language used in these files is a DSL resembling Scala's syntax, but much less complex. To keep it simple, you'll usually just define some values like your project's name and version or dependencies, such as which Scala or SBT versions to use. The names of these values are called "keys". We'll work with only a few of them. Check out the Keys.scala page for a complete list of keys.

For our project we'll specify only four keys. Their names make them fairly self explanatory:

Be very careful with empty lines in the configuration file. Each key-value definition must be separated by an empty line. Now run sbt update in your project's directory.

As you can see, Scala 2.10.1 was automatically selected and downloaded if necessary. We also updated SBT to 0.12.3 on-the-fly. Finally, you'll notice that it calls our project by name when loading: "Set current project to Hellow World".

Directory Structure Conventions in SBT

Even though you can simply put all of your source files into the project's root directory, SBT recommends and uses, by convention, a directory structure similar to Maven. Let's update our directories so that they look like the tree below. You should create only the src directory and its children, the rest were generated when we played with the SBT commands. If they weren't, don't worry, you are only interested in the src directory.


Integrating Scala, SBT, and NetBeans

Now that we've learned the basics of SBT, we need an IDE to write our code. If you prefer to use simple editors, like Sublime Text, you can do so and skip this step.

NetBeans has had support for Scala long before SBT. There's a plugin called "nbscala" that can create Scala projects for NetBeans and use the Scala language installed on the system. At the moment, this plugin is transitioning towards SBT and will eventually have the ability to create and manage SBT projects.

Currently, SBT and NetBeans integrate quite well. The only thing that you have to create manually at the time of writing this article is the initial SBT project. Afterwards, NetBeans can then integrate with it nicely.

Installing Scala Support in NetBeans

Let's open NetBeans, go to Tools/Plugins, select the Available Plugins tab and scroll down to the letter S. Check all of the plugins related to Scala, click Install and let it install the plugins with all of the needed dependencies.

Netbeans Scala Plugin

If you are curious about how this plugin is written, you can check its Github repository.

Installing NetBeans Support in SBT

Yep, you've read it right, SBT has its own plugin system which can generate NetBeans projects for you. You just have to check out a git repository and publish it locally. Change into a directory where you'd like your plugin to be checked out and installed, then run the following commands:

Ok, we're almost done. We have the plugin, now we need to tell SBT to use it. You can do this per project if you wish, but I recommend that you add it to your user's SBT settings: ~/.sbt/plugins/plugins.sbt

The ~ refers to your home directory, you should already have a directory called .sbt in it (note the dot as the first character). You may or may not have a plugins directory, if you don't, just create it and then create the plugins.sbt file. Now add the following to it:

That's it, now your SBT can generate NetBeans projects for you when you run the netbeans command in the SBT console. Alternatively, in NetBeans, you can simply open (not new project, but open) any SBT project and it will automatically generate the NetBeans stuff for you.

NetBeans Open SBT Project

Then all of the project dependencies will be updated and the netbeans command will be run in an SBT console, inside of NetBeans.

NetBeans SBT Console

Now you may see more text scrolling on the screen depending on the dependencies needed to be installed, and you should be able to see that the netbeans command was automatically ran for us.

In the left pane, on the project browser tab, you can even run basic SBT commands by simply right clicking the project and run Reload, Clean, Compile and so on.


Hello World in Scala

Now, this is not a tutorial to learn Scala. We'll only write some very basic code, a classic Hello World. So, you can go ahead and expand your Scala project and in the "Scala Packages" entry, right click on <default package> and select New -> Scala Object. Give it a name, something like "HelloWorld" will do just fine. Then inside of it, enter in the following code:

If you are totally unfamiliar with Scala, an object will automatically run and a method called main will be looked up. The method's definition is just a simple print line of Hello World.

Go to your SBT console for this project - if you closed it by mistake, just right click on the Scala project in the left pane and select Open sbt console. Now, type run in the console, to run the program.

Code and Run Results

Adding Tests

The first step is to install Scalatest so that we have a testing framework. The easiest way to do this is to edit our build.sbt file and add the following line; remember you have to leave an empty line between each line.

Now, in your SBT console you can issue an update (optional) and run the test command. We don't have any tests yet, so the command shouldn't fail.

Test Empty

Creating our first test will be quite easy. The only thing you have to know is that it must be in the src/test/scala folder. Or, if you expand Scala Test Packages in your project viewer and right click on <default package>, you can select New -> Scala Class and create one with the name "ExampleSuite" and add in the code below:

Please note that NetBeans may have a few issues with running your tests, as the Scala plugin is not complete yet. But don't panic, you can still run the tests from the SBT console.

The test just imports the Scalatest test suite FunSuite (where "Fun" comes from functional) and runs two tests. As you might figure out from the code, the first one will pass, the second one will fail.

Tests In Action

If, for some reason, SBT refuses to compile your tests, just close the console in NetBeans, right click your project and select Reload sbt Project. This will fix the issue and your tests will run as expected.


Final Thoughts

There you go! You've just completed your first steps toward learning Scala. I hope this tutorial has helped you to better understand how to get started. If, instead of using Netbeans, which is my preferred IDE, you could also do a Google search to find fairly complete online documentation about how to use SBT & Scala with Eclipse, if that's what you prefer.

Thanks for reading.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.