• Articles
  • Tutorials
  • Interview Questions

Scala Closures - The Definitive Guide

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.

Certification in Bigdata Analytics

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
}

Become a Big Data Architect

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

Course Schedule

Name Date Details
Big Data Course 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Big Data Engineering

Abhijit is a Technical Research Analyst specialising in Big Data and Azure Data Engineering. He has 4+ years of experience in the Big data domain and provides consultancy services to several Fortune 500 companies. His expertise includes breaking down highly technical concepts into easy-to-understand content.