Home/Blog/Programming/Scala tutorial for Java programmers with examples
Home/Blog/Programming/Scala tutorial for Java programmers with examples

Scala tutorial for Java programmers with examples

10 min read
Mar 18, 2021

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Scala is a general-purpose programming, type-safe JVM language 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.

Scala 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 as a powerful language, namely Twitter and LinkedIn. In fact, according to StackOverflow’s 2020 survey, US 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:


Add Scala to your toolbelt

This Scala course will help you stay ahead of the curve, make awesome, scalable apps, and learn a highly coveted programming language.

Learn Scala from Scratch


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 like Kotlin and Ceylon. Scala is unique, however, as it did not try to remain too close to Java’s syntax.

Scala shedded 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, so Scala has a bigger learning curve than Kotlin. But it’s worth the work: it produces clean, simple, organized code that boosts your productivity down the line and requires far less 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 like 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, 3rd party libraries, and community presence than 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:

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

As you can see, Scala is a lot more precise, requiring far less 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 Java, the main method is the entry point for our Scala program, which takes an array of strings as its parameter. The method body has a single call to the method println 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 . HelloWorld

Hello, world!

Scala Syntax Quick Guide#

Now that we know the 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.

widget

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, which stores data of type Int and is assigned an initial value of 55. This is an immutable variable because we chose the keyword val.

In Scala:

  • Variables of type val are immutable
  • Variables of type var are mutable variables

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.

Scala Type Hierarchy
Scala Type Hierarchy

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.

var anyInAction: Any = "A String" //String
println(anyInAction)
anyInAction = 5 //Int
println(anyInAction)
anyInAction = '☺' //Char
println(anyInAction)
anyInAction = 1.985 //Float
println(anyInAction)
anyInAction = true //Boolean
println(anyInAction)

Strings and Literals#

Strings do not fall under anyVal. Rather, they are literals. Strings literals include a combination of characters that are surrounded by double quotation marks. The syntax for declaring a String is the same as 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 decimal regardless of how it is declared. Floating-point literals are used with Double and Float.

val floatLiteral: Float = 1.2345F // The F at the end is for Float
val somethingBigger: Double = 1.2345e1
val evenBigger: Double = 1.2345e4
// Driver Code
println(floatLiteral)
println(somethingBigger)
println(evenBigger)

Keep the learning going.#

This Scala course will help you stay ahead of the curve, make awesome, scalable apps, and learn a highly coveted programming language. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.

Learn Scala from Scratch


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:

widget
var arrayOfEmotions = Array("happy","sad","angry","excited")
if (!arrayOfEmotions.isEmpty) {
arrayOfEmotions(0) = "joyful"
}
// Driver Code
arrayOfEmotions.foreach(println)

The while expression uses the following syntax:

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

The general syntax of a for expression is as follows:

widget

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, which 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.

widget

Objects and Classes in Scala#

Unlike Java, which distinguishes primitive and reference types, Scala treats everything as an object, since Scala 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 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:

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

  def walking = println(s"$name is walking")

  def talking = println(s"$name is talking")

}

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

// Creating an object of the Person class
val firstPerson = new Person 

firstPerson.name = "Mary"
firstPerson.gender = "female"
firstPerson.age = 25


println(firstPerson.name)
println(firstPerson.gender)
println(firstPerson.age)

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.

def square(x: Double) = {
x * x
}
def squareSum(x: Double, y: Double) = {
square(x) + square(y)
}
val result = squareSum(2,5)
// Driver Code
println(result)

Inheritance and Overriding#

There are several types of inheritance supported by Scala:

  • Single-level Inheritance: One class inherits from a single other class
  • Multilevel 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:

class Complex(real: Double, imaginary: Double) {
  def re = real
  def im = imaginary
  override def toString() =
    "" + re + (if (im >= 0) "+" else "") + im + "i"
}

Traits with Scala#

Scala uses Traits, which are similar to Java interfaces. Much like inheritance with Scala like above, a class can also import code from one or more traits. When this happens, a class implements the given trait’s interface and all 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 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:

trait Iterator[A] {
def hasNext: Boolean
def next(): A
}
class IntIterator(to: Int) extends Iterator[Int] {
private var current = 0
override def hasNext: Boolean = current < to
override def next(): Int = {
if (hasNext) {
val t = current
current += 1
t
} else 0
}
}
val iterator = new IntIterator(10)
iterator.next() // returns 0
iterator.next() // returns 1

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 next steps, we recommend the following concepts:

  • Generics with Scala
  • Higher-order functions
  • Currying
  • Scala’s Collection Library

To get started with these concepts and start building with Scala, check out Educative’s course Learn Scala from Scratch. This course will help you stay ahead of the curve, make awesome, scalable apps, and learn a highly coveted new programming language. By the end, you’ll be fully transitioned from Java to Scala!

Happy learning!


Continue learning about Scala and Java#


Written By:
Amanda Fawcett
 
Join 2.5 million developers at
Explore the catalog

Free Resources