Introduction to Functions and Closures in Scala

Function is a block of code which provides the reusability of code. There are two types of functions –

  • Built – in function (Already created i.e. predefined)
  • User defined function (Created by users according to the requirements)


Method in scala is a part of a class which has a name, a signature, optionally some annotations, and some byte code whereas Scala’s function is a complete object which can be assigned to a variable.
Function Declarations:
It has following syntax:

def function_name ([parameters list]) : [return type]

Function Definitions:
It has following syntax:

def function_name ([parameters list]) : [return type] = {
//body of function
return [expression]

e.g.

object add{
def sum( i:Int, j:Int ) : Int = {
var total: Int = 0
total = i + j
return total
}
}

Unit is used when function does not return.It is same as void in Java.

Calling Functions:
Following syntax is used to call function:

function_name( parameter list)

If function is called using instance of object then use dot notation as follows:

[instance].function_name(parameters list)

e.g.

object add{
def sum( i:Int, j:Int ) : Int = {
var total: Int = 0
total = i + j
println(“sum is: “ +total );
}
add.sum(10,20);
}

Output
Sum is: 30
Scala Closures
It is a function which return value is depends on the one or more variables values which are declared outside this function.
e.g.

var value = 20
val sum = (i:Int) => i + value

In this i is a formal parameter whereas value is not a formal parameter.
e.g.

object Intellipaat {
def main(args: Array[String]) {
println( “First operation value: ” +sum(1))
println( “Second operation value: ” +sum(2))
}
var value = 20
val sum = (i:Int) => i + value
}

Output
First operation value: 21
Second operation value: 22
So sum value is depends on the outside variable value.

Previous Next

Recommended Videos