Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
×
UPTO
50%
OFF!
• Live Instructor-led Classes
• Expert Education
• 24*7 Support
• Flexible Schedule

## 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

}

}
```

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 );

}

}
```

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

### "0 Responses on Scala Functions and Closures"

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

## Sales Offer

• To avail this offer, enroll before 25th June 2019.
• This offer cannot be combined with any other offer.
• This offer is valid on selected courses only.
• Cashback will be accumulated in Intellipaat e-wallet
• Please use coupon codes mentioned below to avail the offer