Saturday, January 17, 2015
Like any object oriented programming language Scala allows to define classes which is the code template for creating objects. This article provides a quick introduction to work with Scala classes.

Scala Classes, Fields and Methods

Scala Class is the extensible static code template that can be initiated into objects at run time. Class definition in Scala can take parameters like constructor arguments. 

Scala Fields are member variables that can be accessed anywhere in the class and provide the initial values. 

Scala Methods are member functions that provide the class behavior.

A simple example of a Scala class. Here employeeId and employeeName are constructor fields, field1 is the class field and print is the class method.

class Employee (var employeeId : Int, var employeeName : String) {

  println("Initializing employee ...")
  var field1: Int = 0

  def print() = {
    println(employeeId + " " + employeeName)
  }
  
  println("More initialization ...")
}

To create an instance of a Scala class we use new primitive. In this example, we create an instance of class Employee and invoke a method on the instance.

object EmployeeTest {
  def main(args:Array[String]) {
    val emp = new Employee(5, "John")
    emp.print
  }
}

Scala Class Constructor

The above Employee example produces the following output.

Initializing employee ...
More initialization ...
5 John

In Scala the primary constructor is different from other programming languages like Java/ C++. The constructor fields, statements/ expressions/ methods in the body of the class form the Scala primary class constructor.

For constructor fields and class fields defined as var (e.g. employeeId, employeeName, field1) Scala automatically generates getters and setters which helps to make the Scala code really concise when compared to Java. If the fields are declared as val Scala generates only the getter method.

For example, getters and setters of a constructor field can be accessed as below.

object EmployeeTest {
  def main(args:Array[String]) {
    val emp = new Employee(5, "John")
    emp.print
    emp.employeeId = 6
    println(emp.employeeId)   
  }
}

Multiple Class Constructors

Classes need to have flexibility to provide various approaches to create objects. This is achieved in Scala using auxiliary constructors. There could be multiple auxiliary constructors and each of them need to have a different signature and has to call one of the previously defined constructors.

Let us look at a variation of the Employee class to understand auxiliary constructors. Auxiliary constructors are defined by creating methods named this. Also one constructor calls another constructor using name this.

class Employee1 (var id : Int, var firstName : String, 
    var lastName: String) {

  def this(id : Int) {
    this(id, "", "")    
  }
  
  def this(id : Int, fn : String)  {
    this(id, fn, "")    
  }

  def print() = {
    println(id + " " + firstName + " " + lastName)
  }
}

The Employee class can be created using multiple constructors defined.

object Employee1Test {
  def main(args:Array[String]) {
    val emp1 = new Employee1(5)
    emp1.print
    val emp2 = new Employee1(5, "John")
    emp2.print
    val emp3 = new Employee1(5, "John", "Smith")
    emp3.print    
  }
}

This example produces the following output.
5  
5 John 
5 John Smith

Proceed to read other Scala Tutorials.
Saturday, January 10, 2015
Currying converts a function with multiple arguments into a series of a functions with single argument. This article provides an introduction to Scala Currying Functions.

Scala Currying Functions is often confused with Scala Partially Applied Functions. Both currying and partial application enables creation of derived functions with smaller number of arguments. Key difference is that in currying we get the next single argument function in a series of functions whereas in partial application we get a function with smaller number of arguments.

Let us look at a simple example of curried function.

object ScalaCurryingTest {
  def add(x:Int)(y:Int)(z:Int) : Int = { 
    x + y + z
   }
  
  def main(args: Array[String]) {
    println(add(10)(20)(30))
    val curried = add(10) _ 
    println(curried(20)(30))
  }
}

In this example we define a curried function add with multiple parameter lists. When the curried function is invoked it returns the next single argument function in the series of functions.

Continue to read more Scala Tutorials.
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. Partial application enables conversion of a function with multiple arguments into one with fewer arguments with some values provided in advance.

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.

Contact Form

Name

Email *

Message *

Back to Top