If you ask my colleagues what I think about Scala, they will likely sigh or simply say ‘he likes it a lot’, says Steve Robinson. Scala has so many awesome concepts that aren’t available in most of the popular OOP languages. Here I’d like to highlight my three favourite concepts, to hopefully inspire you to try it.
Simply put, mutability in Scala is given the respect it deserves. Whenever data changes, problems will inevitably arise. One of the simplest questions that can haunt any programmer is:
* Why does this variable hold the value 42?
The more ways this variable can be changed, the more concepts I have to understand in order to solve the problem.
Mutability can be controlled so that a program mostly consists of small side-effect-free functions that take in data and return different data. Scala provides two main ways that help you control mutability.
val vs var
There are two different ways to declare a thing which stores data: var and val. A val is value definition. For example:
val city = “Edinburgh”
It stores a fixed reference to an object. The below code won’t even compile:
ciy = “London”
var is the dangerous one. It stores a reference to an object which can change. For example:
var pi = 3.14159
pi = 42
This is a worrying thought for mathematicians worldwide.
mutable vs immutable data
Typically, Scala’s data classes are immutable, meaning that once I create a String with the contents “Hello World”, it cannot change. Scala also provides both an immutable and a mutable collections library, but it’s the immutable ones that are available by default. You have to add extra code to use the mutable collections, further encouraging developers to use the former.
2. Type Inference
Type inference removes the need to write boilerplate code. This code doesn’t add any value to our program. It is just extra scaffolding required by languages that aren’t clever enough to deduce these things for itself. For example, one way to create a list of Ints in Scala is:
* val list : List[Int] = List.apply[Int](1,2,3);
I’m a big fan of DRY code , so I much prefer to say a thing once. Thankfully Scala can save us in four different ways in this one line:
* val list = List(1,2,3)
3. Case Classes
One common pattern I find is the need for a simple data object. For example, to represent a Person in Scala:
case class Person(
name : String,
height : Double,
location : Double
Creating a new person is rather concise:
val person = Person(“Steve”, 1.8, “The Aquila Edinburgh Office”)
All of the fields are publicly accessible values:
val name = person.name
You can change a property value by calling the copy constructor using named argments to specify which parameter to change:
val updatedPerson = person.copy(location = “home”)
There are many great blogs, courses, and books out there to learn Scala. I’d recommend picking one, getting stuck in and never looking back.