7 min read

In this article by Diego Pacheco, the author of the book, Building applications with Scala, we will see the following topics:

  • Writing a program for Scala Hello World using the REPL
  • Scala language – the basics
  • Scala variables – var and val
  • Creating immutable variables

(For more resources related to this topic, see here.)

Scala Hello World using the REPL

Let’s get started. Go ahead, open your terminal, and type $ scala in order to open the Scala REPL. Once the REPL is open, you can just type Hello World”. By doing this, you are performing two operations – eval and print. The Scala REPL will create a variable called res0 and store your string there, and then it will print the content of the res0 variable.

Scala REPL Hello World program

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> "Hello World"
res0: String = Hello World
scala> 

Scala is a hybrid language, which means it is both object-oriented (OO) and functional. You can create classes and objects in Scala. Next, we will create a complete Hello World application using classes.

Scala OO Hello World program

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> object HelloWorld {
     |   def main(args:Array[String]) = println("Hello World")
     | }
defined object HelloWorld
scala> HelloWorld.main(null)
Hello World
scala>

First things first, you need to realize that we use the word object instead of class. The Scala language has different constructs, compared with Java. Object is a Singleton in Scala. It’s the same as you code the Singleton pattern in Java.

Next, we see the word def that is used in Scala to create functions. In this program, we create the main function just as we do in Java, and we call the built-in function, println, in order to print the String Hello World. Scala imports some java objects and packages by default. Coding in Scala does not require you to type, for instance, System.out.println(“Hello World”), but you can if you want to, as shown in the following:.

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> System.out.println("Hello World") 
Hello World
scala>

We can and we will do better. Scala has some abstractions for a console application. We can write this code with less lines of code. To accomplish this goal, we need to extend the Scala class App. When we extend from App, we are performing inheritance, and we don’t need to define the main function. We can just put all the code on the body of the class, which is very convenient, and which makes the code clean and simple to read.

Scala HelloWorld App in the Scala REPL

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> object HelloWorld extends App {
     |  println("Hello World")
     | }
defined object HelloWorld
scala> HelloWorld
   object HelloWorld
scala> HelloWorld.main(null)
Hello World
scala>

After coding the HelloWorld object in the Scala REPL, we can ask the REPL what HelloWorld is and, as you might realize, the REPL answers that HelloWorld is an object. This is a very convenient Scala way to code console applications because we can have a Hello World application with just three lines of code. Sadly, the same program in Java requires way more code, as you will see in the next section. Java is a great language for performance, but it is a verbose language compared with Scala.

Java Hello World application

package scalabook.javacode.chap1;
public class HelloWorld {
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

The Java application required six lines of code, while in Scala, we were able to do the same with 50% less code(three lines of code). This is a very simple application; when we are coding complex applications, the difference gets bigger as a Scala application ends up with way lesser code than that of Java.

Remember that we use an object in Scala in order to have a Singleton(Design Pattern that makes sure you have just one instance of a class), and if we want to do the same in Java, the code would be something like this:

package scalabook.javacode.chap1;

public class HelloWorldSingleton {
    
    private HelloWorldSingleton(){}
    
    private static class SingletonHelper{
        private static final HelloWorldSingleton INSTANCE = 
               new HelloWorldSingleton();
    }
    
    public static HelloWorldSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
    
    public void sayHello(){
        System.out.println("Hello World");
    }
    
    public static void main(String[] args) {
        getInstance().sayHello();
    }
}

It’s not just about the size of the code, but it is all about consistency and the language providing more abstractions for you. If you write less code, you will have less bugs in your software at the end of the day.

Scala language – the basics

Scala is a statically typed language with a very expressive type system, which enforces abstractions in a safe yet coherent manner. All values in Scala are Java objects (but primitives that are unboxed at runtime) because at the end of the day, Scala runs on the Java JVM. Scala enforces immutability as a core functional programing principle. This enforcement happens in multiple aspects of the Scala language, for instance, when you create a variable, you do it in an immutable way, and when you use a collection, you use an immutable collection. Scala also lets you use mutable variables and mutable structures, but it favors immutable ones by design.

Scala variables – var and val

When you are coding in Scala, you create variables using either the var operator or the val operator. The var operator allows you to create mutable states, which is fine as long as you make it local, stick to the core functional programing principles, and avoid mutable shared state.

Using var in the Scala REPL

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> var x = 10
x: Int = 10
scala> x
res0: Int = 10
scala> x = 11
x: Int = 11
scala> x 
res1: Int = 11
scala> 

However, Scala has a more interesting construct called val. Using the val operator makes your variables immutable, which means that you can’t change their values after you set them. If you try to change the value of a val variable in Scala, the compiler will give you an error. As a Scala developer, you should use val as much as possible because that’s a good functional programing mindset, and it will make your programs better and more correct. In Scala, everything is an object; there are no primitives – the var and val rules apply for everything, be it Int, String, or even a class.

Using val in the Scala REPL

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> val x = 10
x: Int = 10
scala> x
res0: Int = 10
scala> x = 11
<console>:12: error: reassignment to val
       x = 11
         ^
scala> x
res1: Int = 10
scala>

Creating immutable variables

Right. Now let’s see how we can define the most common types in Scala, such as Int, Double, Boolean, and String. Remember that you can create these variables using val or var, depending on your requirement.

Scala variable types at the Scala REPL

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.

scala> val x = 10
x: Int = 10

scala> val y = 11.1
y: Double = 11.1

scala> val b = true
b: Boolean = true

scala> val f = false
f: Boolean = false

scala> val s = "A Simple String"
s: String = A Simple String

scala>

For these variables, we did not define the type. The Scala language figures it out for us. However, it is possible to specify the type if you want. In Scala, the type comes after the name of the variable, as shown in the following section.

Scala variables with explicit typing at the Scala REPL

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.

scala> val x:Int = 10
x: Int = 10

scala> val y:Double = 11.1
y: Double = 11.1

scala> val s:String = "My String "
s: String = "My String "

scala> val b:Boolean = true
b: Boolean = true

scala>

Summary

In this article, we learned about some basic constructs and concepts of the Scala language, with functions, collections, and OO in Scala.

Resources for Article:


Further resources on this subject:


Packt

Share
Published by
Packt

Recent Posts

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

3 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Exploring Forms in Angular – types, benefits and differences   

While developing a web application, or setting dynamic pages and meta tags we need to deal with…

3 years ago

Gain Practical Expertise with the Latest Edition of Software Architecture with C# 9 and .NET 5

Software architecture is one of the most discussed topics in the software industry today, and…

3 years ago