Functions

In this topic, we will see what are Functions and Anonymous Functions.

Functions

Let us understand more about Functions in Scala.

  • A function is a group of statements that perform a task
  • We need to give function name, arguments and argument types for regular functions
  • Functions are expressions (not statements)
  • Functions can be returned, passed as arguments.

Syntax

def functionName(parameters : typeofparameters) : returntypeoffunction = {  
// statements to be executed  
}

Example

def sum(lb: Int, ub: Int)={
var total =0
for (element <- lb to ub) {
total += element
}
total
}
sum(1,10)

Problem Statement

Display the output for given statements

  1. Sum of numbers in a given range
  2. Sum of squares of numbers in a given range
  3. Sum of cubes of numbers in a given range
  4. Sum of multiples of 2 in a given range.

Example

def sum(func: Int => Int, lb:Int, ub:Int)= {
var total = 0
for(element <- lb to ub)
{
total += func(element)
}
total
}
def id(i: Int)= i

def sqr(i: Int)= i * i

def cube(i: Int)= i * i * i

def double(i: Int)= i * 2

sum(id, 1, 10)

sum(sqr, 1, 10)

sum(cube, 1, 10)

sum(double, 1, 10)

Anonymous Functions

  • Anonymous functions need not have a name associated with it
  • Anonymous functions can be assigned to variables
  • Those variables can be passed as parameters
  • While invoking we need to provide the functionality for the parameters which are defined as functions (for parameter i in this case)
sum(i => i, 1, 10)
sum(i => i * i, 1, 10)
sum(i => i * i * i, 1, 10)
sum(i => i * 2, 1, 10)

Share this post