Scala Programming: An Introduction

Scala is a multi-paradigm programming language that runs on the Java Virtual Machine (JVM). In other words, it is a language that supports many different styles of coding, including object-oriented, imperative, and functional programming. The fact that it runs on JVM means that any executable Scala code is guaranteed to yield the same results on a variety of different platforms (A.K.A. portability), including Windows, MacOS, Linux, and Android, among many others.

In this guide, we will show how to get started writing Scala code for both Windows and Linux operating systems. We will also install a user-friendly Integrated Developer Environment (IDE) called IntelliJ that comes packaged with all the tools needed to build Scala Projects, as well as to manage them. Finally, we will introduce a few Scala-supported build tools, which are used to managing packages, libraries, and dependencies for your Scala projects.


How to Install Scala on Windows

Step 1: Ensuring Java Development Kit (JDK) is Installed
First and foremost, we must verify that the Windows machine has JDK installed. To do this, open up the command prompt and enter java -version and javac -version. To work with the latest version of Scala, both Java and Javac versions must be at least 1.8. If needed, you can download the JDK for your machine from Oracle.

Notice the cd command (change directory) at the beginning. If command prompt returned both versions without issue, then you can ignore this. Otherwise, you may have likely encountered the following error after entering javac -version:

If this happens and you are sure that you have installed JDK on your computer, then it is likely that Windows is not looking in the path where the JDK files were installed. The solution is to manually navigate to the directory where the files are, in which case you should use the cd command followed by the directory.

Step 2: Download and Install IntelliJ IDE and the Scala Language
Now we need to download the necessary tools to install and run Scala code.In this guide, we will use the IntelliJ IDE to install and run Scala code, which also comes with necessary tools required to run Scala programs, namely the SBT. You can download .exe installation file from jetbrains. Make sure to download the Community Edition, which is the free version!

Now run the .exe and walk through the installation. There are no specific installation preferences that need to be set, so it is okay to click next and install with default settings.

After the installation finishes, run the IntelliJ IDE and accept the Terms of Agreement. When you reach the welcome window, navigate to configure > plugins.

From the plugins window, find Scala and select Install. If Scala does not immediately show in the results, use the search bar at the top.

After installing, you must restart the IDE to activate changes in the plugins. Click Restart IDE where the Install button was, or simply close and reopen the IDE.

Congratulations! You have successfully installed Scala and a compatible IDE for Windows.

How to Install Scala on Linux

Step 1: Ensuring Java Development Kit (JDK) is Installed
Similarly to Windows, JDK must be installed on the Linux machine. To verify this, open the terminal and enter the commands java -version and javac -version. Again, the latest version of Scala requires both Java and Javac versions to be at least 1.8.

If you receive an error that Java is an unrecognized command, then you need to install the Java Runtime Environment (JRE). This can easily be done by entering the command sudo apt-get install openjdk-8-jre-headless into the terminal. If you get a similar error for Javac, then you are missing the JDK, which you can install with the command sudo apt-get install openjdk-8-jdk-headless.

Step 2: Download and Install IntelliJ IDE and the Scala Language
Now we will download and install the necessary tools to install and work with Scala. The IntelliJ IDE comes with every we need including the necessary build tools, and can be downloaded from Jetbrains.

After downloading the IntelliJ binaries, unpack the files from the terminal with the command tar xfz ideaIC-XXXX.tar.gx, where XXXX is the version number of your download.

Now using the cd command, navigate to the new folder of the unpacked files, and into the bin folder. From here, run the idea.sh file with the command ./idea.sh. This should begin the installation of the IntelliJ IDE.

The installation window should display automatically. As you go through the installation process, you will eventually arrive at a screen for Featured Plugins that gives the option to install Scala. Select Install.

At this point you can click the Start using IntelliJ IDEA button. Congratulations, you have successfully installed IntelliJ and Scala for Linux!


Running a Simple Scala Program: Hello World

We are almost ready to write and run Scala code. Assuming that you have followed our installation guide, the following instructions should work for both Windows and Linux.

Step 1: Creating a New Scala Project in IntelliJ
Begin by opening up IntelliJ, and select Create New Project.

For the project type, select Scala on the left pane, and sbt on the right pane. Then click Next.

Now enter a name for your project, such as HelloWorld. Next to the sbt and Scala versions, make sure to check the boxes that say sources. DO NOT press Finish yet!

Before we can continue, we must set the JDK. Click New, and navigate to the folder where your JDK is installed. Then click OK.

Now we can click Finish and let IntelliJ generate the project structure. IntelliJ will synchronize the necessary dependencies for sbt, and will let you know when it finishes in the console.

Next we will add the Scala SDK to our project. This is a CRUCIAL but one-time-only step, so this step will no longer be necessary for creating a new Scala project after this. Right-click on your project in the project pane, and select Add Framework Support.

Select Scala, and notice that there is no library selected. Click the Create button.

In the resulting window, click download. Confirm the Scala SDK version you want and click OK.

The Scala SDK should apply itself automatically once finished downloading, and the library should now indicate that it is using the SDK.

Finally, we are done setting up the project, and are ready to write Scala code. In the project pane, navigate to HelloWorld > src > main > scala. Right-click the scala folder, and select New > Scala Class.

In the resulting window, click the drop-down menu and change the Kind to Object. Give a name to your new object and click OK.

IntelliJ should automatically create an outline of the code for your new object. We will slightly modify it so it may perform the typical Hello World function:

Now let’s run our code! From the menu bar, select Run > Run.

Now select the object you just created.

If all goes well, the console at the bottom of the IDE will display the program output, and confirm that your program successfully executed and terminated.

Now you are ready to start experimenting with Scala code! Remember that Scala runs on the JVM, therefore the same code can be executed on almost every platform, assuming that all of the dependencies and SDK/JDK configurations remain compatible. For a head start on the language’s syntax and features, check out the Scala Cheatsheet featured on the official Scala website.


Managing Packages, Libraries, and Dependencies

Many programmers use package managers to easily automate the installation, removal, and configuration of software packages for their programs. In the case of Scala, various build tools are used according to the requirement of the program, instead of package managers. We will now look at some of the most used build tools, their functions, and how they affect the building of the program.

sbt — simple build tool

sbt is the one of the most well known build tool used for Scala. It was the first build tool and hence consists of a large set of plugins and integrations. It is for this reason that it is one of the most reliable build tools used in Scala programming.

Installing sbt
sbt can be downloaded and installed from different sites for different OS. For Windows, MSI can be used for the installation. For Mac, sbt is available on Homebrew, and can be installed by using the command brew install sbt@1. For Linux such as RedHat or Debian, packages can be used for the installation of sbt.

Creating a New Project
sbt consists of different templates which help while creating a new project. For example Giter8 is one such template which can be used to create a new project. Different templates can be used according to the need of the program like for a simple project, scala-seed template can be used.

This is how a scala seed template looks like for creating a simple project:

Defining the Build
A build.sbt file located at the root of the project is used by sbt to define the build of the program. More build definitions can be added to the project directory as Scala files. Using the template we end up with the following code:

Running the Project
To run a project using sbt build tool we have 2 options. One option is to run the program using the command line shell directly. The other option is to use the sbt-shell, which comparatively faster than using the command line. The sbt shell can be started simply by starting sbt with the command sbt:sbt-test>

Dependencies in sbt 
Dependencies in sbt should be structured for better building of the program. The dependencies are added using sbt’s DSL.

The %% notation is used to mark the dependency. The important thing to make sure is using the correct dependency according to the Scala version. These dependencies can be added using the library settings with the += operator.

Defining Custom Tasks:
sbt allows the users to define their own tasks, resolution and definition layer.

The task key is used to define the task. This acts as an interface with type, name and description of the task. For example, in the above code, name is taskKey, type is string, and the description is in the parenthesis. All that is left is to implement the interface.

Documentation, Community, and Plugins
sbt documentation is very refined and complete. Since sbt has been around for longer than most other Scala-supported build tools, its community is fairly extensive, and has acquired a large number of plugins, most of which are mentioned in the Github organization.

Cbt — Chris’ build tool

Cbt is an abbreviation of Chris’ Build Tool. It was created by Christopher Vogt as an additional build tool apart from sbt. Unlike sbt, Cbt maps the execution of task to JVM invocations and does not add its own layer in between.

Installing Cbt
For the installation of cbt, cbt repository is cloned and the directory is added to the path. Use the command git clone https://github.com/cvogt/cbt.git.

After the execution for the first time, it suggests using nailgun for faster execution. In Homebrew, nailgun can be installed with the command brew install nailgun.

Creating a New Project
After the installing Cbt, we can use it to create a new project.

Defining the Build
If there is already a defined build file, then cbt will use it to set its build settings. We can also let cbt create a new build file.

Running the Project
In sbt, we had option of using common shell or the sbt shell. But in Cbt, there is no individual shell so the tasks has to be executed directly from the common shell.

Dependencies in Cbt
sbt DSL is supported in Cbt, which helps in incorporating dependencies from README files using copy and paste. Apart from that, ScalaDependency and MavenDependency can be used to express the dependencies, though these would have to be nested under a Resolver.

Defining Custom Tasks
In Cbt, creating custom tasks is very easy. One only need to create a new function in the build file and call the task from the Cbt afterwards.

Documentation, Community and Plugins
Cbt is not as vast as sbt but it does have a few plugins and a small community. The documentation would be helpful in the start but you would have to learn on your own after some time.

Mill

Mill is rather young build tool as compared to other but contains most of the functionalities of sbt. It is faster, easier and simple. In a nutshell better than sbt. The reason for this is, with sbt one can do a thing in many ways which sometimes results in user doing many unnecessary things to do one thing. In Mill, you only have one way. It provides faster initialization and updates the build files automatically, in case anything is changed.

Installing Mill
For windows, Mill can be installed by simply downloading the bat file. For Linux, an AUR package can be downloaded. For OS X, Mill is available on brew package, and can be installed from brew package with the brew install mill command.

Creating a New Project
Mill currently doesn’t have any method or mechanism to generate a new project.

Defining the Build
The build file is defined in the root file of the project.

The above code shows how the build definition in Mill looks like. The build structure of the project looks as follows:

The structure of project in Mill is almost like the structure of Maven. Mill doesn’t pose any restriction on the structure but instead allows the flexibility of the modules. Its structure is also sbt compatible.

Running the Project
Mill has a module.task file which dictates a common syntax for the project.

Dependencies in Mill
Like sbt, Mill also uses DSL to add dependencies to the project, only instead of using %% for dependencies Mill uses :: notation.

Defining Custom Tasks
Mill handles task definition, ordering and cache by using its own defined task graph abstraction. When one task is called from another, it creates dependencies. There are 3 different types of tasks:

  1. Targets: It is used to define where the output is generated,compiled or assembled.
  2. Sources: It defines where the code is originated from.
  3. Commands: it defines the things to do. For example, a task defined as:

will produce the following output:

Documentation, Community and Modules
Mill has a complete documentation at http://www.lihaoyi.com/mill/ and a very active community. Mill uses modules instead of plugins.

Other Build Tools

There are many build tools other than the ones we covered; too many to be discussed extensively in a single guide. For example, there is Gradle, which can also be used as a build tool for the scala project using Gradle-Scala plugin. There is also Fury, a fairly new build tool recently launched, whose documentation and community is only starting to grow. We also have Maven and Polyglot Maven, which can be used if one wants to use Maven in their project. At the time of this writing, there are also some build tools currently in early development , such as Ant, Bazel, Pants, and Make.

How to choose a Build Tool?

Since each build tool specializes in different programming needs, the decisive factor in choosing the build for you should be based on your needs. If you’re considering a specific build tool to use, checking the documentation would be a good place to start.

sbt is the most effective and popular build tool used for Scala programming. For simple projects with straight-forward needs which are well documented, sbt can be used. Sbt is mostly used by experienced programmers. For beginners, using sbt for the parts which are not documented will be really difficult, so in these cases it is well suggested to use Mill instead of sbt.

Authors:
Alessandro Heres — Github
Tristen Sprainis — Github
Ayushi Priyadarshi — Github | LinkedIn