bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Scala Functions and Closures

 

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.

"0 Responses on Scala Functions and Closures"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

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

top

Sales Offer

  • To avail this offer, enroll before 05th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Scala Functions and Closures.