Introduction to Functions and Closures in Scala
The 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)
The method in scala is a part of a class that 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 the following syntax:
def function_name ([parameters list]) : [return type]
Function Definitions:
It has the 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
}
}
The unit is used when the function does not return. It is the same as a void in Java.
Calling Functions:
Following syntax is used to call a function:
function_name( parameter list)
If the function is called using an instance of the 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
The sum is: 30
Scala Closures
It is a function in which the return value depends on the one or more variables values that 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.