Want to get started in functional programming? Enter Scala.
By: Rhea Moutafis
Tags: Software Development, Functional Programming, Programming Languages, Towards Data Science, Scala

Opinion

Want to get started in functional programming? Enter Scala.

If you’re bored of Java or Python, this might bring your career to the next level

Scala might be the next step to becoming a functional programmer. Photo by Nicole Wolf on Unsplash

If you haven’t used Scala yet, you’re not the only one: Not even four percent of all programmers were using the language as of last year, according to StackOverflow. That puts it at rank 22 of the most-used languages, JavaScript and HTML being the top two.

The programmers that use Scala, however, seem to profit from it. Not only does it rank at place 14 in StackOverflow’s most loved languages. This is significantly higher than the rank 22 of usage.

And financially, knowing the language seems to pay off: Globally, only Perl programmers get a higher salary than Scala programmers, both landing at around $76 thousand per year. In the US, Scala takes the top spot in terms of salary, and programmers can expect to make about $150 thousand each year. Sounds okay to me!

There are different reasons why some programming languages are more loved or more lucrative than others. In the case of Scala, the main reason is that it makes it quite easy for programmers to learn functional programming, without giving up on known-and-loved paradigms like object-oriented programming.

Functional programming has been gaining traction in the past few years because it’s very apt for processing big data volumes, implementing machine learning algorithms, and more. As such technologies scale very well, investing in them has been bringing revenue in companies of uncountable sectors. That’s why high salaries for Scala-programmers are justified.

Unifying object-oriented and functional programming

Scala certainly isn’t the only multi-paradigm language on the market. Python, for example, supports both object-oriented and functional programming. In Java, functional programming is possible in principle, even though it’s originally designed as an object-oriented programming language.

What makes Scala special, however, is its quest to seamlessly integrate object-oriented and functional programming. Usually, the two paradigms are presented as the opposite of one another: in functional code, you’ll only find pure functions. In object-oriented code, you’ll come across impure functions, too.

In functional code, all variables are immutable, i.e., their values are fixed once and never changed again. In object-oriented code, you can change the values of variables as you go. In functional code, you won’t find any side effects; in object-oriented code, you could encounter them from time to time.

That doesn’t mean that there aren’t many ways to include more functional programming in code that is primarily object-oriented. In many languages, you can use basic concepts that are stolen from functional programming in your regular code. For example, in Python, it’s quite easy to build iterators, generators, and anonymous functions.

But Scala does this the other way around, too: it makes it very easy for developers to write primarily functional code which can then be patched up with object-oriented pieces where functional would be a bit too tedious. This is a nice compromise to purely functional programming, where things like user-defined I/O, for example, aren’t straightforward to implement.

Getting started in Scala isn’t as hard as it sounds. Photo by Priscilla Du Preez on Unsplash

Quickstart in Scala

Like in many other languages, there are two ways of working with Scala: using an IDE, or on the command line. Personally, I’m a command line-aficionado, but at the end of the day that comes down to taste.

In both cases, however, you’d have to download and install Scala. But sometimes you just want to dabble a bit first without installing anything or follow along with what I’ll be presenting in the following sections — which I encourage you to do. The good news is that you can write and run your code right in your browser with Scastie or ScalaFiddle.

Both sites are fine for smaller projects like the one down below, where you won’t be loading a lot of libraries. If you need to load something heavy, then ScalaFiddle might be the better option because it handles libraries quite efficiently.

It goes without saying that, for the moment at least, code-in-browser projects shouldn’t be huge. If you’ve developed a liking for Scala and you want to build something bigger, then installing Scala on your machine will be the better option.

That being said, it’s completely fine if you don’t have the time to follow along right now. By the end of this story, you’ll still be able to understand what’s going on, and have a basic understanding of how to code in Scala.

Scala’s “Hello, World!”

Go to Scastie or ScalaFiddle, and type:

println("Hello, world!")

Then press “run”. And you get Hello, World! It’s that simple.

Okay, if you want to run a real script on your local machine, you do need some boilerplate code. But we’ll get to that in a minute. First, there are a few basics that we’ll need to cover.

Values and variables

You can assign immutable variables — in Scala they’re called values — using the val prefix:

val Greeting = "Hello, World!"

println(Greeting)

Since values are immutable, you can’t reassign anything to them. If you try to, the compiler will throw you an error. You guessed it right: that’s functional programming right there!

There is an alternative, though, if you need to reassign something: just use the prefix var , and call it a day.

Scala is both object-oriented and functional. Photo by 7shifts on Unsplash

Functions and methods

Functions are constructed really easily in Scala:

val GreetMe = (name: String) => println("Hi, " + name + "!")

GreetMe("Rhea")

This returns Hi, Rhea! as expected. The part before the = defines the name of the function, then come its arguments, and after the => you’ll find the function body.

You can define anonymous functions by leaving away the name definition, which is very much in the style of functional programming. What’s not functional at all is that you can define functions that have no arguments — in functional programming, you always need an argument.

There are also methods, which are quite similar to functions:

def GreetMe2(name: String): Unit = {

val greeting = "Hi, " + name + "!"

println("Hi, " + name + "!")

}

GreetMe2("Rhea")

They’re quite similar to functions, but their syntax is a bit different. An output type needs to be specified, like the Unit in front of the curly braces in this example.

On a more theoretical level, functions are generalizations of methods. That’s because methods are always a part of a class. Functions can be part of a class but don’t need to; if they happen to be part of one, they’re called methods instead.

Classes and objects

Classes are defined as follows (this I directly copied from the Tour of Scala):

class Greeter(prefix: String, suffix: String) {

def greet(name: String): Unit =

println(prefix + name + suffix)

}

Then I can define an instance of that class in the following way:

val GreetMe3 = new Greeter("Hello, ", "!")

GreetMe.greet("Rhea")

Calling the method greet in the class is done in the same way that you’d do it in Python or in other languages.

Objects in Scala are instances of their own definitions:

object HowManyGreets {

private var counter = 0

def greet(): Int = {

counter += 1

counter

}

}

Unlike classes, they can’t take any parameters. They do return things, though, when you call their methods:

val onegreet: Int = HowManyGreets.greet()

println(onegreet) // outputs 1

val twogreets: Int = HowManyGreets.greet()

println(twogreets) // outputs 2

Putting it all together

There’s one special object, the main method, that is the entry point of every Scala program. This is similar to Python, Java, or C and C++, where you’ll come across the main method, too.

So let’s write a main method that can greet me:

object Main {

def main(name: String): Unit =

println("Hello, "+ name + "!")

}

val greettheworld: Unit = Main.main("World") // Hello, World!

Perfect! If you’d be working on your command line or IDE, you’d save this piece as Hello.scala . Then you’d compile and execute it like this (the $ indicates that this is happening in your shell):

$ scalac Hello.scala

$ scala Hello

Congratulations! Not only have you understood how to write your first little program in Scala. You’ve also gained some background knowledge about the concepts that constitute this program.

Scala is excellent for functional programming. Photo by DISRUPTIVO on Unsplash

Getting functional in Scala: higher-order functions and nested methods

We’ve already encountered a few basic concepts of functional programming in Scala, for example, immutable variables and anonymous functions. Other phenomena that occur quite often in functional programming are functions that take or return other functions, and methods that are defined inside one another.

These things are possible to do in object-oriented programming, too. But in functional programming, they arise naturally and occur quite often. In object-oriented programming, these phenomena are somewhat rare encounters.

Higher-order functions

Say you’re doing similar operations over and over again. Often it’s easier to define a function that does everything these operations have in common, and sub-functions that do whatever is different in each operation.

For example, let’s say we’re trying to perform different operations on a list. Maybe we’d like to add 2 to each element, or we’d like to square each element. You could write one function, calcAnything , that performs any calculation on a function. Then you write different functions for adding 2 or squaring the elements:

object CalcSomething { private def calcAnything(numberslist: List[Double], calcFunction: Double => Double): List[Double] =

numberslist.map(calcFunction) def add2(numberslist: List[Double]): List[Double] =

calcAnything(numberslist, number => number + 2) def square(numberslist: List[Double]): List[Double] =

calcAnything(numberslist, number => number * number) }

The map function inside calcAnything takes care that the operation takes place on the list. We can call these functions like before:

val newList = List(1.2, 4.5, 3.6) val squared: List[Double] = CalcSomething.square(newList)

println(squared) // output: List(1.44, 20.25, 12.96) val plustwo: List[Double] = CalcSomething.add2(newList)

println(plustwo) // output: List(3.2, 6.5, 5.6)

Note that when plustwo gets executed, the operation gets performed on the list as it was defined in the beginning. That’s a direct consequence of functional programming: variables like val are immutable. If you wanted to apply these operations sequentially, you’d need to use squared as an argument of add2 .

Likewise, we can define functions that return other functions. There’s a neat example in the Scala Docs if you’re interested in digging deeper. For the sake of brevity, I won’t further elaborate on it here.

Nested methods

Like in many other languages, you can define functions inside one another. One neat example would be to calculate the sum of all integers up to a particular number:

def bigSum(x: Int): Int = {

def sum(x: Int, summator: Int): Int = {

if (x < 1) summator

else sum(x - 1, x + summator)

}

sum(x, 0)

} println("Sum of 0 to 8: " + bigSum(8)) // outputs 36

println("Sum of 0 to 100: " + bigSum(100)) // outputs 5050

println("Sum of 0 to 0: " + bigSum(0)) // outputs 0

You can verify this with the Gaussian sum formula: The sum of any sequence of integers up to an integer n is S = n⋆(n-1)/2.

Getting object-oriented in Scala: classes, side-effects, and more

If you know Java, Python, C++, or another major programming language, it’s unlikely that you haven’t heard of object-oriented programming. And I’m sure that throughout this piece you’ve recognized some concepts!

Starting with the main method which carries the prefix object , all the way to classes and methods within classes, the basic constituents of object-oriented programming are all present in Scala. Side-effects, i.e., arguments of functions that weren’t explicitly declared, are also easy to implement: for example, it’s possible to define a function without any arguments — but technically, every function needs some kind of argument, even if it’s just self !

If you’re a dedicated functional programmer, the only object-oriented thing that you won’t get around is the main method. But if your comfort zone is in the realm of what’s object-oriented, you’ll be covered, too.

What makes Scala stand out from other languages

Most popular programming languages of today started out object-oriented, and are now integrating more and more features of functional programming as demand is rising. Think of Python, Java, or Perl for more context. Scala, on the other hand, has been poised to integrate both from day one.

It’s not the only language that started out as a mix of programming paradigms. Go, for example, also makes use of many different ones. The makeup and simplicity of Go makes it amazing for microservices, systems architecture, and such problems.

On the other end of the spectrum is Rust: as a language, it’s harder to learn than Scala, and much harder to learn than Go. Like Scala and Go, it mixes paradigms, but it also has some unique features of its own. Learning all that means that you could easily take two weeks before you’re productive.

Rust is used for many of the same problems as Scala, i.e., big data processing, machine learning, parallel programming, and more. But if you want to get productive quickly and not get too inundated with heavy jargon (or have you ever heard of monoids, arity, or foldables?), Scala might be the better option.

If you’re not scared away from mathematically loaded jargon and other peculiarities, then Rust is also worth a go. This applies in particular if you plan to keep going in functional programming in the long term. For beginners in functional programming, however, I’d recommend Scala.

Learning new languages together with others can be particularly encouraging. Photo by Brooke Cagle on Unsplash

Where to learn more

If this article motivated you to download Scala and try it for yourself, the getting started page of Scala is where you need to go.

Scala comes with rather excellent documentation. The site also provides you with some nice online resources that are worth checking out.

If you’re a hands-on learner (I know I am), then these two tutorials are worth checking out. For a more structured approach and lots of neat examples, check out the Tour of Scala. And for a deeper dive, check out the Scala Book.

The bottom line: Scala might be more than lucrative for your career

If you up your game in Scala, that could result in a serious boost in terms of salary. But that’s only one side of it all.

Scala provides you with enough object-oriented programming that you’ll feel like you’re on familiar ground. At the same time, it’s an excellent way to get to know functional programming at your own pace.

Functional programming is excellent for anything big data, machine learning, and the like. And demand for those areas isn’t stalling anytime soon.

It’s uncertain whether Scala is the one language that will dominate functional programming. I’d rather treat Scala as a stepstone to learning the concepts of an extremely important programming paradigm.

Whether you stick with Scala, go back to Python or Java and add more functional snippets to your code, or whether you move on to more complex languages like Rust — that’s entirely up to you. Even if you don’t stick with Scala, it just might be your door-opener to getting to grips with functional programming.