Writing Functions in Scala

This post is looks at the various ways in which one can write functions in scala. Yes, there are multiple ways to write functions and also there are short hand forms if your function is only a line.

Functions declaration syntax:
// def functionName(arg): ReturnType = { content… }

There is no need to put a return keyword as the last thing in the function body if your function returns something. By default, the last expression in the function body is treated as the return value by scala.

//Function definition. There is no return statement becoz by default 
// last statement in the function body is treated as return
 def add(x: Int, y: Int): Int = {
//Invoked the function
scala> add(10,20)
res0: Int = 30

Scala can automatically infer the return type if the return type is not specified in function declaration.

def square(n: Int) = n * n // Scala Compiler automatically infers return type is Int

Short Hand Notation

If the function body is a single expression there is no need to use the { } and can be omitted.

//Shot hand notation. There is no {} 
def add(x: Int, y: Int): Int = x+y

Parameter Ordering in Functions

Scala allows changing the order of parameters passed to the function during its invocation by allowing to specify the parameter name and value. This is very handy and easy to understand with an example

// This function just appends two strings with a | separator in between
def printText(a: String, b: String): String = {
        s"$a | $b"

output: Hello | world

//change parameter order

output: world | Hello

Default Parameters

Scala allows functions to have default values to fallback, in case a value was not provided during the function invocation.

def multiply(n1:Int,n2:Int =2) = n1 * n2

output : 30

//second parameter is not passed
output : 20

Anonymous Functions

Anonymous functions allows developers to just provide the function logic without the need to associate it with a name. Anonymous functions are often used as arguments being passed to other functions. Anonymous function or lambda can be assigned to a variable and can be passed around.

//Syntax of anonymous (lambda) function in scala
(a: Int) => a + a

The above function has no name and is not associated with a body with {}

//Passing anonymous functions - Example
 val lst = List(10,20,15,19)

//An anonymous function is passed to the filter function of List
// This simple function filters out all elements that are even

lst.filter((n:Int)=> n%2 != 0)
//output : List(15, 19)

If you want to use the lambda function multiple times the function can be assigned to variable and used many times as needed.

//Assingn lambda to a variable
scala> val t = ((n:Int)=>n%2 != 0)
t: Int => Boolean = $$Lambda$865/2104281815@4d9ad37e

scala> lst.filter(t)
res7: List[Int] = List(15, 19)

You can even reduce the function logic to a simpler form using shortcuts provided by scala. For instance lst.filter(_%2!=0) will do for a simple operation like removing all even numbers.

Another option is scala even allows to omit the input types of anonymous function if the type can be understood from the context. This is at times confusing for new developers. I will explain this in detail to bring more clarity.

Typical anonymous function declaration syntax is (a: Int) => a + a

Here the type of input parameter ( Int ) is mentioned. But this can be avoided if the given context makes it clear as in. val result: Int => Int = a => a * a

Here a => a * a ( the one after the = ) is the function body and we have avoided explicitly mentioning the type of a ( a: Int) because it is evident from the variable declaration ( result).


Leave a Comment