Saturday, December 13, 2014
To invoke functions requires us to specify all the function parameters. Scala provides a construct called Partially Applied Functions where a function invocation can be reused by retaining some of the parameters without the need to type them again.

Let us look at an example to understand the partially applied functions. Here we have basic function multiply to get the product of two numbers. We create two partially applied functions multiplyBy3 and multiplyBy5. Missing argument is substituted with an _ underscore. 

object PartiallyAppliedFunctionsTest {
  
  def multiply(x: Int, y: Int) : Int = { x * y }
  
  // Partially applied functions
  val multiplyBy3 = multiply(_:Int, 3)
  val multiplyBy5 = multiply(_:Int, 5)
  
  def main(args:Array[String]) {
    println(multiply(6,2))
    println("Partial function multiplyBy3 = " + multiplyBy3(6))
    println("Partial function multiplyBy5 = " + multiplyBy5(6))
  }
}

This example produces the following output.

12
Partial function multiplyBy3 = 18
Partial function multiplyBy5 = 30

It is also possible to create a partially applied function where all arguments would be passed during function invocation. For example,

val multiply1 = multiply _

Scala provides the syntactic convenience to use single _ (underscore) in this case.

Continue to read more Scala Tutorials.
Sunday, December 7, 2014
Scala  supports a facility to avoid naming functions. This provides convenience when working with higher order functions where the need is to pass a function as a parameter to another function. These are referred to as anonymous functions or function literals

A simple anonymous function.

(x : Int) => x * x 
Here x : Int is the parameter and right side is the body of the function.

An example of anonymous function with multiple parameters.

( x: Int, y : Int) => x + y

Another example of anonymous function with no parameters.

() => { Calendar.getInstance().getTime() }

Anonymous functions can be saved into vals.

scala> val add = (x : Int, y : Int ) => x + y
add: (Int, Int) => Int = <function2>

scala> add(10, 20)
res1: Int = 30

Benefits of anonymous functions can be observed when working with higher order functions. In this example we have a higher order function which returns a function as a result. The higher order function giveMe takes a String as input and returns a function (anonymous function) which takes two Int's as input and returns an Int.

object HigherOrderFunctionTest1 {

  // Higher order function
  def giveMe(t : String) : (Int, Int) => Int  = t match {
    case "sum" => (x, y) => x + y
    case "sub" => (x, y) => x - y
    case "mult" => (x, y) => x * y
    case "div" => (x, y) => x / y
  }

  def main(args: Array[String]) {
    println(giveMe("sum")(20, 10))
    println(giveMe("sub")(20, 10))
    println(giveMe("mult")(20, 10))
    println(giveMe("div")(20, 10))
  }
}

Proceed to read other Scala Tutorials.
Saturday, December 6, 2014
Scala is also a functional programming language and allows the definition of higher order functions. Functions that take other functions as parameters or whose result is a function are called higher order functions (HOF). In Scala functions are treated as first class values which can be passed as parameters and returned as a result.

Let us look at some simple examples to understand Scala higher order functions.

Higher Order Function - Function as a parameter

In this example we have a higher order function compute which takes a function as a parameter. Here 'f' is a function which takes two arguments of type Int and returns an Int.

f : (Int, Int) => Int

The higher order function takes another function 'f' and values 'arg1' and 'arg2' as input and applies function 'f' to the values 'arg1' and 'arg2'.

object HigherOrderFunctionTest {
    
  def sum ( a : Int, b: Int ) : Int = { a + b }
  def sub ( a : Int, b: Int ) : Int = { a - b }
  def mult ( a : Int, b: Int ) : Int = { a * b } 
  def div ( a : Int, b : Int ) : Int = { a / b }
  
  // Higher order function
  def compute(f : (Int, Int) => Int, arg1: Int, arg2 : Int) : Int = {
    if ( arg1 > 0 && arg2 > 0 )
      f(arg1, arg2)
    else
      0
  }
  
  def main(args: Array[String]) {
    println(compute(sum,20,10))
    println(compute(sub,20,10))
    println(compute(mult,20,10))
    println(compute(div,20,10))
    println(compute(div,20,0))
  }
}

Higher Order Function - Function as a result

In this example we have a higher order function which returns a function as a result. The higher order function giveMe takes a String as input and returns a function which takes two Int's as input and returns an Int represented as (Int, Int) => Int.

object HigherOrderFunctionTest1 {

  // Higher order function
  def giveMe(t : String) : (Int, Int) => Int  = t match {
    case "sum" => (x, y) => x + y
    case "sub" => (x, y) => x - y
    case "mult" => (x, y) => x * y
    case "div" => (x, y) => x / y
  }

  def main(args: Array[String]) {
    println(giveMe("sum")(20, 10))
    println(giveMe("sub")(20, 10))
    println(giveMe("mult")(20, 10))
    println(giveMe("div")(20, 10))
  }
}

Proceed to read other Scala Tutorials.
Wednesday, December 3, 2014
Scala is also a functional language and provides the flexibility to the programmer to use classes and methods as in a object oriented language along with pure functions. Functions in Scala are also objects. This article provides a brief introduction to using functions in Scala.

def is keyword used to define functions in Scala. A Scala function definition is typically of the form,

def FunctionName ( arg1 : Type, arg2 : Type ) : ReturnType = {
  Expression
}

As a simple example let us consider a Scala function to add two numbers.

object Foo {
  def sum ( arg1 : Int, arg2 : Int ) : Int = {
    arg1 + arg2
  }
  
  def main ( args : Array[String] ) {
    println(sum(10,20))
  }
}

Some key aspects when working with Scala functions.
  • Function parameters always need an explicit type specification though type inference can be used for variables in Scala.
  • Return type need not be specified.
  • return keyword can be omitted if the last expression is what needs to be returned
  • Using return type as Unit is same as using void in Java.
  •  
    def doSomething () : Unit = {
       println("I am a function")
    }
    
  • Leaving out equal sign (=) in function definition is a common mistake when working with Scala functions. When a function doesn't return anything it is ok to ignore the equal sign. It is a good practice to always put equals sign even when the function doesn't return anything.

Default Parameter Values

Scala supports specifying default values for function parameters like Java.

object Foo {
  def compute ( arg1 : Int, arg2 : Int, arg3 : Int = 1 ) = {
    ( arg1 + arg2 ) * arg3
  }
  
  def main ( args : Array[String] ) {
    println(compute(5,10))
    println(compute(5,10,2))
  }
}

Function with Variable Arguments

Scala supports functions with variable number of arguments for the last parameter.

object Foo {
  def doSomething ( input : Int* ) = {
    for ( arg <- input ) {
      println(arg)
    }
  }

  def main ( args : Array[String] ) {
    doSomething(10, 20, 30)
  }
}

Proceed to read more Scala Tutorials.
Saturday, November 29, 2014
This article provides a brief introduction to an interesting concept the Scala Companion Object.
  • Scala doesn't have static variables and methods. Scala Companion Object can be visualized as a place holder for all the static variable and method needs of a Scala class. 
  • Scala Companion Object has the same name as an associated Scala class and needs to be specified in the same source file.
  • Scala Companion Object can be used to initialize a class with different set of parameters.
  • Scala Companion Object can be used to implement factory design pattern.
A simple example to introduce Scala Companion Object. Here we have a class Foo and its companion object Foo. Companion object is used to initialize this class with different set of parameters.

class Foo ( x : Int, y : Int ) {
  println(x, y)
}

object Foo {
  
  def get {
   new Foo1(0, 0)
  }
  
  def get ( x : Int ) {
    new Foo1(x, 0)
  }
  
  def get ( x: Int, y : Int ) {
     new Foo1(x, y)
  }
  
  def main(args: Array[String]) {
    val f1 = Foo get
    val f2 = Foo get(10)
    val f3 = Foo get(10, 20)
  }
}

Let us look at a companion object example to implement a Factory design pattern. In this example, we have a class Shape and an object Shape. Here object Shape is the companion object to class Shape. The companion object takes on the factory method responsibilities and creates the requested Shape object.

Scala provides syntactic flexibility to avoid clutter in the code by using apply() method. In the example, instead of an explicit call to apply() method we use Shape("Square") which is a kind of shortcut to call the apply method.

abstract class Shape

private class Square extends Shape { println("Created Square") }
private class Circle extends Shape { println("Created Circle") }
private class Cube extends Shape { println("Created Cube") }

object Shape {
  def apply(shapeType : String) {
    shapeType match {
      case "Square" => new Square
      case "Circle" => new Circle
      case "Cube" => new Cube
    }
  }
  
  def main(args : Array[String]) {
    val sq = Shape("Square")
    val cr = Shape("Circle")
    val cu = Shape("Cube")

    // All of these are same as above
    val sq1 = Shape.apply("Square")
    val sq2 = Shape apply("Square"
    val sq3 = Shape apply "Square"
  }
}

This scala program produces the following output.

Created Square
Created Circle
Created Cube
Created Square
Created Square
Created Square

Proceed to read other Scala Tutorials.

Contact Form

Name

Email *

Message *

Back to Top