Quick introduction to functions in Scala

So, as you might already know, Scala is a functional language. This means that it is heavily based on functions (Scala actually mixes Object Orientation and Functional Programming).

Lets take a look on how to use functions in Scala. It is really fun, after you get the feel for it.

First, you must know that in Scala, almost (if not) everything can be used as a function identifier. An example:


This will  result in, obviously, 3. It is even like Scala had operator overload, except that +, , / and * are not exactly operators in Scala. They are functions, like everything else. Take a look at the scaladoc for the Int class, and notice all the functions for those operators.

Of course, the code above is really ugly. So you should write it like this:

1 + 2

and the Scala compiler takes care of transforming it to the previous example. And what’s more: this is not any kind of special case. This is valid for any function. So, instead of writing this:


you could write this:

calculator sum(2,3)

Dumb example, but nice anyway, isn’t it?

Something more interesting now. If you are used to Javascript, you are used to sometimes pass functions around to other functions. Scala allows us to do the same thing:

def operationTest(operation: (Float, Float) => Float): Float = {

The code above declares a function, operationTest, that receives another function, operation, which receives two Floats and returns a Float as well.

The operationTest function then calls the function it received. The result of operationTest is whatever results from operation – in Scala, the return value of a function is always the result of the last statement in it.

You can exercise operationTest this way:

// returns 8.0
operationTest( (x: Float, y: Float) => x + y )

// returns 2.0
operationTest( (x: Float, y: Float) => x - y )

// returns 1.66666666
operationTest( (x: Float, y: Float) => x / y )

// returns 15.0
operationTest( (x: Float, y: Float) => x * y )

So in the code above, we are declaring anonymous functions and passing them to operationTest, which then executes whatever function it received.

Here, (x: Float, y: Float) is the function header, or declaration, and everything after => is the function body: x + y, x – y, x / y and x * y in these cases. Notice also that we are not declaring the functions’ return types. Scala infers them from the execution of the body, and thus from the type of the parameters.

That’s it for now. Willing to learn something in specific about Scala? Post a comment and let me know! I’m in the quest for mastering this language, so challanges are much appreciated! =)

This entry was posted in scala and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s