Scala 101: a beginner's guide to the scalable language

Amanda Fawcett
Nov 20, 2019
editor-page-cover

Scala is an exciting programming language that has been gaining popularity across the industry. Some say it may even replace Java. If you’re looking to learn Scala or you’re just curious about what it has to offer, you’re in the right place. Here’s what we will go over today:

  • Part 1: Scala FAQs

  • Part 2: Introduction to Scala Syntax and Tools

  • Part 3: Resources for Learning/Practicing Scala

If you want to get started learning Scala for free, check out our beginner’s course


Part 1: Scala FAQs

What is Scala?

The Scala programming language was created in 2001 by Martin Odersky to combine functional programming and object-oriented programming into one language. The name is an acronym from Scalable Language. Scala was designed to improve upon Java, so you can call Java methods, inherit from Java classes, and more. In fact, Java libraries can even be incorporated in Scala code, and Scala is compiled in Java bytecode, so it is executed in the JVM (Java Virtual Machine).

For a brief introduction to Scala, check out our blog post here

What is Scala used for?

Scala is commonly used for strong static systems, data science, and machine learning. Scala is used in finance-related applications, content management systems, online learning platforms, distributed applications, and more.

What companies hire Scala programmers?

Companies like Google (for Android, Twitter, LinkedIn, Sony, Quora, and Foursquare use Scala regularly in their programs. Other companies such as Apple, The Guardian, Meetup, Verizon, SoundCloud, Airbnb, and Duolingo use Scala in certain teams or have released statements that they will be switching to Scala.

Why should I learn Scala?

  1. It’s in high demand: Scala is increasingly popular in certain markets. Big companies are hiring more and more Scala programmers as the language becomes more popular. Learning the language will make you more in demand for the changing market.

  2. Scala syntax is precise: Compared to Java, Scala syntax is quite precise, making it more readable yet more concise.

  3. Scala pays well: Scala recently ranked 4th for the programming language with the highest salary. Scala developers in the US are some of the highest paid globally.

  4. The best of both worlds: Scala combines the benefits of OOP with Functional Programming, making it a stronger, more efficient language. Scala also combines the good qualities of statically typed and dynamic languages.

  5. Scala is growing: Both the online community and Scala frameworks are growing, so there is lots of innovative information out there. Even some Java developers are joining in and switching to Scala. According to StackOverflow, Scala ranked 17th for most wanted language.

  6. Scala has cool features: Scala brings with it many cool features to make your life easier including immutability, type interface, pattern matching, string interpolation, traits, an extensive collection of classes, and lazy computation.

Is Scala similar to Java?

There are some similarities since Scala is a new generation JVM language. They are both object oriented and both produce the same bytecode. They also have similar libraries and compilers (called javac and scalac).

The main difference is Scala’s ability to handle Functional Programming and multi-core architecture. Scala’s syntax is also more succinct, but learning Scala is generally a bit harder than Java since it combines both paradigms. Scala also supports Operator overloading and has a built-in lazy feature to defer computation while Java does not.

What is Apache Spark?

Apache Spark is a general-purpose distributed processing engine with four different APIs that support languages Scala, Python, R, and Java. Spark also provides libraries for SQL, machine learning, and stream processing. Spark is written in Scala, so you will often see Scala and Spark together. Since you’re just starting out, this isn’t important yet, but know that you may see Spark-related content as you learn about Scala.


Part 2: Introduction to Scala Syntax and Tools

Your path to learning Scala largely depends on your familiarity with other programming languages, like Java, C++, or Haskell. It is possible to learn Scala from scratch, but it will be easier with a few minimal prerequisites, such as a basic understanding of Object Oriented Programming and programming terminology. Here is the general progression of what lies ahead:

  • Install the proper tools/programs
  • Learn Scala basics and syntax
  • Understand Scala functions
  • Understand how Scala uses object oriented programming
  • Understand mutable and immutable collections
  • Learn Apache Spark
  • Get familiar with Scala Frameworks and Libraries

Today, we will walk you through the tools and basics of the Scala language to get you started. Let’s jump right in!


Overview of Tools and Programs

First, get access to Scala

To do this, you’ll need the Java 8 JDK. The Java Development Kit (JDK) is technology package that can be used for compiling Scala code into Java bytecode. The JDK including the JVM (Java Virtual Machine), where code is executed. Once you have the JDK, there are two popular options for a Scala environment. Either approach is fine.

  1. Get Scala through sbt: sbt is an open source, interactive tool for building Scala programs. It is the Scala build. tool. This is where you can test and compile your code, as well as integrate frameworks.

  2. Get Scala through an IDE: An Integrated Development Environment (IDE) packages all the tools to help us write and execute Scala code. A popular IDE for Scala is IntelliJ IDEA. By downloading a Scala plugin for IntelliJ, you can use it as a Scala development environment. There are other text editors you can use, such as Eclipse, NetBeans, Vim-scala, and VS Code.

Second, look into libraries and frameworks

Libraries and frameworks are like collections of prewritten code to make your life easier as a Scala programmer. You can integrate these into your code to save time and effort. They also provide really neat features for making interactive and dynamic programs. There is a long list of Scala libraries and frameworks, but don’t let this overwhelm you. The frameworks and libraries you use largely depend on your unique needs, so you’ll likely figure this out as you go. Here are a few of the most popular to get you started:

  • Akka: framework for distributed processing
  • Slick: database query and access library for stored data
  • Scalaquery / squeryl: Scala databases
  • Finagle: open access RPC from Twitter
  • scalatra: minimalist HTTP framework
  • Play and lift: for web development and applications

Basics of Scala Syntax

The syntax of a programming language is the set of rules for how you write code and make different components interact. It defines the different parts of your code, giving them meaning, functionality, and relationships to other parts of your program. Think of syntax like the grammar of a language. Let’s take a look at an example of some Scala code and then break down the syntax piece-by-piece.

If you’re already familiar with Java and want to jump right into Scala, check out our free beginner’s course

First, a very simple Scala program: the Hello World statement

object Main extends App {
    println("Hello world!")
}

This program uses a method, which is a statement that performs a particular action. The print method tells the program to print whatever is in the parentheses. The text in parentheses is called a string. In Scala, a string is an immutable object, meaning it cannot be modified.

Now, look at a more complicated Scala program, which prints the complementary secondary color of an inputted primary color.

var testVariable = "red"
 
testVariable match {
  case "blue" => print("orange")
  case "yellow" => print("purple")
  case "red" => print("green")
  case _ => print("not a primary color")
}

Here, you can see the same print method as above, but instead we are using control structures, pattern matching, and variables to print a more complex expression. This expression looks for conditions and matches our input based on the requirements. Since the variable red matches the case “red”, it prints green.

Tip: Always save your Scala fils as .scala

Now that you are familiar with how Scala looks, let’s break it down further and go over some of the basic definitions and syntax rules.


Identifiers

Identifiers are used to identify class names, method named, variable names, and object names. There are six kinds of identifiers in Scala: GRG (class); a (variable name); main (method name); Main (object name); ob (object name); and args (variable name).

Here are the rules you must follow for making identifiers.

  • Scala identifiers are case-sensitive.
  • A keyword cannot be an identifier.
  • Identifiers cannot start with numbers.

Keywords

Keywords are reserved words used for naming actions. You cannot use these are variable or object names. Take a look at the list below:

Objects and Classes

An object in Scala is an entity with a state and behavior that can be manipulated. These are similar to objects in other programing languages. Similarly, classes in Scala are like the blueprints or templates for our various objects. These define properties and behavior. Classes are defined with the keyword class. The code below defines a class of people and then defines an object — a person — to go within that category.

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")

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

Variables

In Scala, you declare variables using keywords var (mutable variable) or val (immutable variable). Each kind of variable takes a string value. For example var Var1: String = “Scala”. Once you create your variables, you can perform operations on them using operators.

Operators

Operators act upon your variables. There are several different categories of operators: Arithmetic, Relational, Logical, Bitwise, and Assignment. These are similar to operators in other programming languages. For example, you can add two variables using the + arithmetic operator.

def sum(x: Double, y: Double): Double ={
x+y
}

Let’s break that down

  • def is the keyword used for defining a function, and sum is the name of the function.
  • sum is followed by ( ). This is where define the function parameters separated by commas. Parameters specify the type of input to be given to the function.
  • (x: Double, y: Double) tells us that our function takes two parameters, x and y, that are of type Double.

Functions and Methods

Functions are a group of statements that perform actions. You can reuse functions in your code and apply it to various variables or objects. For example, we could make a function that multiplies an integer by 2 (see code below). You create functions using the def keyword. Since functions perform actions, you need to define if it returns a value or not.

A function definition can appear anywhere in a Scala file. Functions can have names with characters such as, +, ++, ~, &,-, --, , /, :, etc.

Functions are similar to methods, and sometimes they are used interchangeably. A Scala method, however, is a part of a named class, whereas a function is an object itself that can defined to a variable.

def mul2(m: Int): Int = m * 2
Output: mul2: (m: Int)Int

In functional programming, functions are treated as first-class values, meaning that they can be passed as a parameter to another function. These are higher-order functions called nested functions.

Data Structures

There are six kinds of data structures in Scala: Arrays, List, Sets, Tuple, Maps, Option. Arrays and List are the most common.

  • Arrays: an array is a collection of similar elements. In Scala, arrays are immutable.

  • List: lists are a versatile data structure compiled of items that have the same type. They are immutable in Scala. You must declare a list using List and defining the different items.

Control Structures

A control structure analyses variables and makes decisions based on predetermined parameters. There are a few different types of control flow structures in Scala, which are similar to other programming languages. Scala brings a function approach to an imperative paradigm, so you have more control abstraction.

  • if...Else: This classic programming decision-making tool makes a decision based on whether an expression returns true or false. For example, a program can test if a number is less than 5, and if it is, it will return “Less than 5”

  • while: a while loop in Scala states that a body of code will continue to be executed as long as a condition is met.

  • for: the for loop iterates over values in a collection, checking if there are elements we wish to iterate over. If those elements exist, it goes to the next value. If now, it exits the code.

  • try: try is used to test particular parts of code for exceptions. If an exception is thrown, it is caught using caught so you do not get an error.

  • match: this is used for pattern matching, where we take an object and match it to a list to finds it predefined match. We used this in our example when red was matched to green.

Now that you have a basic sense of Scala syntax and vocabulary, it’s time to dive into actually practicing! Let’s go over some resources that will help you put this new Scala knowledge into practice.


Part 3: Resources for Learning Scala

As the Scala community grows, so do the amazing resources available to you online. When questions come up or you get stuck, the answer is likely already waiting for you. Take a look at the free resources at your fingertips.

Forums / Online Communities

  • Reddit: online community for questions and inspiration

  • GitHub: leading open-source online community for questions/resources

  • StackOverflow: open-source online forum for questions, resources, and data

  • Glitter: Scala programmer chat room

Blogs and Newsletters

Style Guides / Cheatsheets

Scala Practice

Online Courses

If you want to learn Scala online, there’s no better time to start. You can visit our free course, Learn Scala from Scratch, to get started on your Scala journey. The highly interactive course offers a roadmap for all you need to know to master Scala quickly. Here’s what it covers:

  • The History of Scala
  • Variables and Types
  • Operating with Operators
  • Strings in Scala
  • Collection Library
  • Control Structures
  • Functions / Higher-Order
  • Functions in Scala
  • Classes and Objects

Learning something new is already challenging enough. That’s why we’ve made our course completely free. Taking that first step comes at no extra cost to you. You’ll get lifetime access without any sneaky subscription fees.

Start learning Scala today!

WRITTEN BY

Amanda Fawcett


A free, bi-monthly email with a roundup of Educative's top articles and coding tips.