Scala combines two programming paradigms: object oriented and functional. As a result you get best from the two worlds. From the one side you can describe models as objects, from the other side you can apply functions to them. And as you may guess, it’s really awesome! Let’s discover today basics of Scala functions.

Every time when you need to perform some business logic or simple action, start writing a function. With help of functions you can do almost everything. Why “almost”? Because to describe a model you still need use classes and objects.

Function syntax

Functions can work with arguments and perform actions with them. Functions can return values. You can make a compositions from multiple function in order to complete one complex task. And all this is wrapped in a flexible syntax. So how to create a function in Scala? Here is how a simple function declaration looks like:

def welcomeUser(name: String): Unit = {
    println("Hello, "+name)
}

This function prints a greeting. The greeting contains a name which is passed to the welcomeUser function as a parameter. And what about that weird word Unit in the first line? It indicates that the function doesn’t return anything.

After a function is declared we can use it. In order to call a function we need to write its name and pass parameters into it.

welcomeUser("Alex")
//the output is "Hello, Alex"

Here is another example of Scala function:

def isEven(number: Int): Boolean = {
    if (number % 2 == 0)
        true
    else
        false
}

The function above accepts an integer number as a parameter and returns a boolean value. It’s logic is pretty trivial, it check is the number argument even or odd.

Here is a general pattern for a function declaration in Scala:

scala-function-syntax

At first you need to write a def keyword. The next step is to write a function name. If the function needs some arguments you write them in the brackets in a format name: Type, otherwise brackets remain empty. Then you specify a return type of the function. And finally you write a function body.

More function examples

Now let’s consider several more examples of functions. We can start from the pretty useless function, which doesn’t has any arguments and prints some string:

def uselessPrint(): Unit = { println("Ho-ho-ho") }

What about a function which takes more than one parameter?

def taxCalculation(amount: Double, tax: Int): Double = {
    (amount / 100) * tax
}

In the example above we create the taxCalculation(amount: Double, tax: Int) function, it accepts two parameters and calculates taxes based on them. Pay your attention to the function body. Its last line has a Double type (after calculation). A type of the last line (last expression) in the method is a type which a function return.
Here is how this function looks like in the REPL:

Scala-function-with-multiple-arguments

Also Scala allows to omit a return type in a function declaration. But anyway Scala knows what function returns due to type inference. We have discussed the type inference in the previous post about the variables.

def stringCutter(str: String, length: Int) = {
    val result = str.substring(0, length)
    result
}

Here is what happens in the REPL when we declare this function and use it:

Scala-function-returning-type

There are a lot of syntax elements which can be omitted when you are working with functions in Scala, e.g. curly brackets if a function body suits well for single line. Let’s rewrite the taxCalculation(amount: Double, tax: Int):

def taxCalculation(amount: Double, tax: Int) = (amount / 100) * tax

Functions under microscope

As was told in the previous post, everything in Scala is object. Functions are not exception. So actually, all functions which we have demonstrated in the current article are objects. Scala has some sort of abstractions for functions depends on number of their arguments, starting from 0 (function without arguments) to 22 (yeah, imagine an ugly function with 22 parameters!).

Using these abstractions you can also define functions, but it’s not elegant way, just look at this:

val taxCalculation = new Function2[Double, Int, Double] {
    def apply(amount: Double, tax: Int): Double = (amount/100)*tax
}

This is absolute equivalent of the function which calculates taxes in the previous paragraph. This code sample is provided just for demonstration of the functions nature, they are objects. Here is how it looks like in the REPL:

Scala-function-object

Default values

Sometimes it’s very handy to define default values for function parameters. Scala allows to do this in a really convenient form:

def makeOrder(total: Double, payment: String = "cash", coupon: Boolean = false) = {
    println(s"Total: ${total} \nPayment: ${payment}\nCoupon: ${coupon}")
}

makeOrder(12)
//Total: 12.0 
//Payment: cash
//Coupon: false

makeOrder(12, "visa", true)
//Total: 12.0 
//Payment: visa
//Coupon: true

makeOrder(12, coupon=true)
//Total: 12.0 
//Payment: cash
//Coupon: true

As you see you can set default values directly in a function declaration. And then you are able to call the function with lower number of arguments, because the missing ones will be populated with the default values. Moreover you can override particular arguments by calling them explicitly during the function invocation.

Summary

Functions in Scala are the smallest building blocks for a business logic. They are really powerful and can be used in many situations for different purposes. In this post we overviewed the basics of functions and their syntax. There are a lot of things which you need to know about them, e.g. what is functions composition or how to pass functions as argument to another function. But this is topics for other posts.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close