Scala Tutorial for Java Programmers (With Examples)

A starting point for Java developers looking to transition towards Scala

The Educative Team
Better Programming

--

Orange background with learning material
Image by the author.

Scala is a general-purpose, type-safe programming JVM language that offers support for object-oriented programming (OOP) and functional programming. Scala was designed to address some of the limitations and tediousness of Java.

It is a great option for Java developers who want to take their career to the next level (or for those who are just tired of Java’s quirks). Scala is now recognized by big companies — namely Twitter and LinkedIn — as a powerful language. In fact, according to Stack Overflow’s 2020 survey, U.S. Scala developers have the highest-paying salaries.

If you are a Java developer who wants to transition to Scala (or just see what it has to offer), you’re in the right place. Today, we will introduce you to Scala to make the transition.

This tutorial at a glance:

  • Scala vs. Java
  • Hello World With Scala
  • Scala Syntax Quick Guide
  • Objects and Classes in Scala
  • Inheritance and Overriding
  • Traits in Scala
  • Next Steps for Your Scala Journey

Scala vs. Java

Java is known for its complexity and verbosity. It requires a lot of lines of code to perform simple tasks. Scala was designed to create a “better Java,” much like other alternatives such as Kotlin and Ceylon. Scala is unique, however, as it did not try to remain too close to Java’s syntax.

Scala shed the restrictive and tedious aspects of Java in favor of making a better language overall.

This means that there are some notable distinctions and paradigm shifts between the two. As a result, Scala has a bigger learning curve than Kotlin. But it’s worth the work. It produces clean, simple, and organized code that boosts your productivity down the line and requires far fewer lines of code than Java.

There are several key differences between the languages. Let’s break them down.

  • Scala is a statically typed language.
  • Scala uses an actor model for concurrency (instead of Java’s thread-based model).
  • Scala doesn’t use static members.
  • Scala variables are immutable by default.
  • Scala supports multiple inheritances with classes (not abstract classes).
  • Scala supports lazy evaluation, unlike Java.
  • Scala offers support for operator overloading.
  • Scala doesn’t offer backward compatibility.
  • Scala can be used for functional programming.
  • Any Scala method or function is treated as a variable, whereas Java treats them as objects.
  • Scala uses traits instead of Java interfaces.

One of the main advantages of Scala is that it can be executed on the Java Virtual Machine (JVM), making it very easy to interact with Java code. All classes from the java.lang package are imported by default with Scala.

One of its drawbacks, however, is community support: There is less detailed documentation, community presence, and fewer third-party libraries than with Java. However, this is changing as more Java developers add Scala to their toolbelt.

For a practical example of how Java and Scala differ, let’s see how we’d create a list of Strings in both languages:

// java
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
// scala
val list = List("1", "2", "3")

As you can see, Scala is a lot more precise, requiring far fewer lines of code. Scala is also easier to skim, making it a great choice for teams.

Hello World With Scala

Now that we are familiar with the main differences between Java and Scala, let’s dive into some more code to understand how these two languages differ. First, look at the Hello World program in Java that we’re familiar with:

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

Now, look at an equivalent program in Scala. You’ll notice right away that it’s somewhat similar:

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

So, what is going on here? Just like in Java, the main method is the entry point for our Scala program that takes an array of Strings as its parameter. The method body has a single call to the println method with our greeting as the argument. Since the main method doesn’t return any value, its type is Unit.

The thing that may stand out to you is the use of the object declaration. This introduces a singleton object, which is a class with a single instance. Here, we are defining a class called HelloWorld and an instance of that class of the same name.

You may have also noted that the main method is not declared static. Scala does not support static members, so we define them as singleton objects.

Compiling code with Scala

Compiling our code is also a bit different here. For our Scala example above, we’d use scalac, which works like most compilers. For Scala, the object files that its compiler produces are Java class files.

So, say we saved our Hello World program in a file called HelloWorld.scala. We’d use the following command. This will generate some class files, including one called HelloWorld.class:

> scalac HelloWorld.scala

Once we compile our program, we can run it with the scala command, which is just like the java command:

> scala -classpath . HelloWorldHello, world!

Scala Syntax Quick Guide

Now that we’ve covered a Hello World program with Scala, let’s quickly look at some basic Scala syntax that you’ll need to know. We won’t be defining terms here, as it’s assumed you already know them from Java or another language.

Variables

First, variables. Here’s how we declare a variable in Scala:

Declaring a variable in Scala

Compare this to Java’s syntax, which follows this basic structure:

<variable type> <variable identifier>;

In our Scala code, we declare a variable with the name myFirstScalaVariable that stores data of type Int and is assigned an initial value of 5. This is an immutable variable because we chose the keyword val.

In Scala, variables of type val are immutable, while variables of type var are mutable.

Data types

Scala has a type hierarchy with type Any at the top. Any is the super-type that defines universal methods such as equals, hashCode, and toString.

Diagram explaining Scala data types
Diagram by the author.

Any has two subclasses: AnyVal and AnyRef. AnyRef is for reference types, including types defined by Scala users. AnyVal represents our value types, of which there are nine:

  • Double
  • Float
  • Long
  • Int
  • Short
  • Byte
  • Char
  • Unit
  • Boolean

Below, we have a variable anyInAction of type Any. We can assign anyInAction a value of any type:

Output:

A String
5

1.985
true

Strings and literals

Strings do not fall under anyVal. Rather, they are literals. String literals include a combination of characters that are surrounded by double quotation marks. The syntax for declaring a String is the same as for declaring a variable of any basic value type.

val stringLiteral: String = "Hello"// Driver Code
println(stringLiteral)

Integer literals are used with the value types Long, Int, Short, and Byte. Scala will always print an integer literal as a decimal regardless of how it is declared. Floating-point literals are used with Double and Float.

Output:

1.2345
12.345
12345.0

Control structures

Scala’s control structures are if, while, for, try, match, and function calls. In Scala, control structures return values like functions.

The if expression has the following syntax:

If syntax

The while expression uses the following syntax:

While syntax
var count = 1
while (count <= 10) {
println(count)
count += 1
}

The general syntax of a for expression is as follows:

For syntax

A generator defines a named variable and assigns it to a set of values. We construct it with three parts: a variable, a <-, and a generator expression.

for (i <- 1 to 5) {
println(s"iteration $i")
}

User-defined functions

We can define functions in Scala. Take a look at this example that takes two integers and returns their sum:

def sum(x: Double, y: Double): Double ={
x+y
}
  • def is the keyword for defining a function.
  • sum is the given name of the function.
  • sum is followed by (). This is where you define the function parameters separated by commas.
  • (x: Double, y: Double) tells us that our function takes two parameters: x of type Double and y of type Double.
  • We define the return type of the function,Double, by inserting : Double after the (). Inserting the return type is not required.
  • Then we insert a =. Whatever comes after this is the body of the function. The body of the function is wrapped in curly brackets ({}).

Note: You can choose not to use the curly brackets if the function’s body only consists of a single expression.

Example of user-defined function

Objects and Classes in Scala

Unlike Java, which distinguishes primitive and reference types, Scala treats everything as an object since it is a pure OOP language. In Scala, numbers are also treated as objects, so they also have methods. Take the following arithmetic expression:

1 + 2 * 3 / x

This expression is made with method calls since it is the same as the following expression, so + and * are valid identifiers in Scala.

1.+(2.*(3)./(x))

Classes

In Scala, classes are declared much like in Java, but Scala classes can have parameters. Look at this basic class definition in Scala using the class keyword and var keyword to define our properties (called fields in Scala):

class Person{
var name: String = "temp"
var gender: String = "temp"
var age: Int = 0
}

To define the methods of our class, we use this syntax:

And now we can create instances of our classes using val:

Calling functions within functions

In Scala, functions are also treated as objects, so we can pass functions as arguments, store them in variables, or return them from other functions. This is one valuable feature of functional programming that Scala provides.

Take a look at this example below where we are calling the function square in the other function SquareSum:

Inheritance and Overriding

There are several types of inheritance supported by Scala:

  • Single-level inheritance: One class inherits from a single other class.
  • Multi-level inheritance: One class extends another, which then extends another.
  • Multiple inheritance: One class inherits from multiple base classes.

In Scala, all classes inherit from a superclass, and when no superclass is declared, Scala uses scala.AnyRef. You can override methods that are inherited from a superclass, but you must explicitly specify this using the override modifier. For example:

Traits in Scala

Scala uses traits, which are similar to Java interfaces. Much like inheritance with Scala, a class can also import code from one or more traits. When this happens, a class implements the given trait’s interface and all the code in that trait. Think of this as a way to implement reusable behavior in Scala code.

The basic properties of a trait are:

  • Traits specify the signature of the methods that a given class supports.
  • Traits are declared like classes with the trait keyword. Take a look at this example:
trait Iterator[A] {
def hasNext: Boolean
def next(): A
}

In Scala, we can use the extends keyword to extend a trait. Then, we implement any abstract members with the override keyword:

Next Steps for Your Scala Journey

Congrats on making it to the end. You’re now well on your way to transitioning to being a Scala developer. As you can see, Scala empowers you to utilize your existing Java skills. There is still a lot to learn about Scala, and hands-on practice will be essential to mastering this language.

For your next steps, we recommend the following concepts:

  • Generics with Scala
  • Higher-order functions
  • Currying
  • Scala’s collection library

Happy learning!

--

--

Master in-demand coding skills with Educative’s hands-on courses & tutorials.