Scala Tutorial for Java Programmers with examples
Tags: scala, java, languages
Published: 2021-03-18 18:46:39

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:**
* [Scala vs Java](#vs)
* [Hello World with Scala](#hello)
* [Scala Syntax Quick Guide](#quick)
* [Objects and Classes in Scala](#objects)
* [Inheritance and Overriding](#inheritance)
* [Traits in Scala](#traits) 
* [Next steps for your Scala journey](#next)

<br>
<a name="vs"></a>
 
## 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](https://www.educative.io/blog/multithreading-and-concurrency-fundamentals) (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](https://www.educative.io/blog/what-is-functional-programming-python-js-java)
* 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:

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

```scala
// scala
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. 


<br>
<a name="hello"></a>
 
## 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:

```java
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.

```scala
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. 

<br>

### 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`.

```scala
> scalac HelloWorld.scala
```

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


```scala
> scala -classpath . HelloWorld

Hello, world!
```

<br>
<a name="quick"></a>


## 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](https://www.educative.io/blog/learn-java-from-scratch) or another language. 

<br>

### Variables 

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prtyw7zhtdt8kq6y1r7x.png)

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

```java
<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 *5*. 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

<br>

### 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`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rn6j6r3cske6xt6mzam9.png)

`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.

```scala
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)
```

> **Output:**
> A String
> 5
> ☺
> 1.985
> true

<br>

### 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.

```scala
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`.

```scala
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)
```

> **Output:**
> 1.2345
> 12.345
> 12345.0

<br>

### 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:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kjhu8dsi7vioag2cg14.png)

```scala
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:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmj1gcpjv8pwltynv4wy.png)

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

The general syntax of a `for` expression is as follows:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plllza30ep45lrhzj0bh.png)

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

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

### User-defined functions

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

```scala
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.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x93tqmeqnthh0kj2guls.png)

<br>
<a name="objects"></a>

## 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](https://www.educative.io/blog/object-oriented-programming).  In Scala, numbers are also treated as objects, so they also have methods. Take the following arithmetic expression:


```scala
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.

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

<br>

### 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).

```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:

```scala
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`.

```scala
// 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)
```


<br>

### 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`. 

```scala
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)
```

<br>
<a name="inheritance"></a>
 
## Inheritance and Overriding

There are several types of [inheritance](https://www.educative.io/blog/java-inheritance-tutorial) 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:


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

<br>



<a name="traits"></a>
## 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:


```scala
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:

```scala
// from Scala documentation 
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
```

<br>
<a name="next"></a>


## 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.
](https://www.educative.io/courses/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!*

<br>

### Continue learning about Scala and Java
* [Scala 101: a beginner's guide to the scalable language
](https://www.educative.io/blog/scala-101-a-beginners-guide)
* [What is functional programming? Explained in Python, JS, and Java](https://www.educative.io/blog/what-is-functional-programming-python-js-java)
* [The resurgence of Scala in 2020](https://www.educative.io/blog/the-resurgence-of-scala-in-2019)