Scala Notes: Functions

Functions in Scala can be defined simply as follows:

def fnname (args)={ 
  // function body
}

def double(i:Int) = i*2 

Implementing loop can be done in following manner.

def whileLoop{
  var i = 1
  while (i<=3) {
    println (i)
  }
}

Function that takes other functions as a parameter, or that returns a function as the result, are called higher order function. One thing that is particular to functional programming is that it treats function as value. This provides a flexible way to compose programs.

def totalResultOverRange(number:Int, codeBlock: Int => Int):Int = {
    var result = 0;

    for ( i <- 1 to number) {
     result = result + codeBlock(i)
    }

    return result;
}                                               //> totalResultOverRange: (number: Int, codeBlock: Int => Int)Int


totalResultOverRange(11, i => i)                //> res0: Int = 66

totalResultOverRange(11, i =>if (i%2 == 0) 0 else 1)
                                              //> res1: Int = 6

totalResultOverRange(11, i => 1)                //> res2: Int = 11
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s