Thursday, January 19, 2012

Functional Programming on the JVM

Scala
Scala is a statically typed multi-paradigm programming language designed to integrate features of object oriented programming and functional programming. Since it is static, one cannot change class definition at run time i.e. one cannot add new methods or variables at run-time. However Scala does provide functional programming concepts i.e. immutability, higher-order functions, nested functions etc. Apart from supporting Java's concurrency model, it also provides concept of Actor model out of the box for event based asynchronous message passing between objects. The code written in Scala gets compiled into very efficient bytecode which can then be executed on JVM.
Creating immutable list in Scala is very simple and doesn't require any extra effort. "val" keyword does the trick.
 
val numbers = List(1,2,3,4)

Functions can be passed as arguments. Let's see this with an example.
Suppose we have a list of 10 numbers and we want to calculate sum of all the numbers in list.

val numbers = List(1,2,3,4,5,6,7,8,9,10)

val total = numbers.foldLeft(0){(a,b) =>

    a+b

}
As can be seen in above example, we are passing a function to add two variables "a" and "b" to another function "foldLeft" which is provided by Scala library on collections. We have also not used any iteration logic and temporary variable to calculate the sum. "foldLeft" method eliminates the need to maintain state in temporary variable which would have otherwise be required if we were to write this code in pure Java way (as mentioned below).
 

int total = 0;

for(int number in numbers){

    total+=number;

}
Scala function can easily be executed in parallel without any need for synchronization since it does not mutate state.
This was just a small example to showcase the power of Scala as functional programming language. There are whole lot of features available in Scala to write code in functional style.
 

No comments: