Home » JVM Languages » Scala » Functional Programming in Scala

About Raghavan Muthu

Raghavan Muthu
Raghavan alias Saravanan Muthu is an IT professional having more than 12 years of experience on Java SE/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is presently working as a Technical Architect for one of the largest public sector banks of India to handle the e-Messaging application for running several fixed and seasonal campaigns. He has completed his Post Graduation (Master of Science) in Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Mater of a non-profit charity organization named SHaDE (http://shade.org.in).

Functional Programming in Scala

In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language.

According to Wikipedia, the definition of Functional Programming is as follows.

In computer science, functional programming is a programming paradigm – a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Pre-requisite: The readers are expected to know the basics of Java and Scala Programming.

The following table shows an overview of the entire article:

1. Environment

The examples in this article are executed in the Command Prompt / Shell with the Scala Interpreter. But they are guaranteed to work with any of the IDEs (like Eclipse – Scala IDE, IntelliJ IDEA etc.,) through the respective plugins. The examples are executed with the Scala Version: 2.11.7 in Windows 7.

You may refer to my previous tutorial here on how to install Scala, if you are a beginner with Scala.

2. Two different but major Programming Styles

In the world of Computer Programming, there are quite a few paradigms being used, right from Procedural to Object Oriented to Functional Programming. We will consider the Procedural and Functional Programming practices for our discussion in this article.

Though FP (Functional Programming) appears to be a new buzzword, it had been in the industry since many decades right from Lisp, Erlang though it was originated from Lambda Calculus. However in the recent past this style has been acquired in the newly evolved Programming languages like Scala, Ruby, Clojure etc.,

2.1 Imperative or Procedural Programming

Imperative or Procedural Programming is a style in which you being a Developer or Programmer will instruct the computer with every step to perform the task solving a problem. It is more of you telling How to do alongside what to do.

Most of the high level Programming languages like C, C++ and Java followed Imperative Programming styles. The main disadvantage of this style is the way a state of the variable is changed during the execution of the program, as typically these languages preferred various different looping control structures like for, while and do-while etc., and within these looping structures a temporary variable (called as a flag or an interim variable depending on the context) which gets changed for every iteration of a collection in a loop. This is actually called as a state change of a variable which can be either local to a method or global to a class in which the method is defined.

Moreover, the actual code involved in doing the work will be detailing every minute step of a problem being solved.

2.2 Imperative Programming – Sample Code

Let us understand the same with an example. Let us write a program in Java to find the first Odd number from a list of Integers.

FindFirstOddNumber.java

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class FindFirstOddNumber
{
  public static void main(String... args)
  {
    // Arrays.asList() will return an ArrayList from the list of numbers
    List intList = Arrays.asList(2,4,5,6,7);
  
    System.out.println("Input List : " + intList);
    
    boolean found = false;

    for(int i : intList)
    {
      if(i%2==1)
      {
        System.out.println("Found the first odd number - " + i);
        found = true;
        break;
      }
    }

    if(!found)
    {
      System.out.println("No odd number present in the list");
    }
  }
}                                                                                        

The code above is very simple. We have a list of Integers (intList) to be iterated for finding out the Odd numbers if any present. If there is one, we will print the number being found and then stop the iteration immediately so as to avoid the rest of the processing which is unnecessary.

Let us see the output of the above program.

C:\Users\javaPgms\> java FindFirstOddNumber
Input List : [2, 4, 5, 6, 7]
Found the first odd number - 5

As expected, the program first printed the input list of Integers and then printed the first odd number 5 and exited.

The main reason for having this sample program is to see the actual things happening in the program. If you see the line number 14, we have a meaningful temporary variable (flag) named found to be used for stopping the iteration. We also use the value of the same flag at the end of the program to determine whether or not an odd number was found in the input list. Likewise, we have a temporary looping variable called i which is used inside an enhanced for loop (it is called as foreach loop) where the value of i is changed with the new value (element at the current index) for every iteration.

These are the two changes we are doing in the small and simple program, where we are not just saying what this program should do, but we are also saying how this program will work. This is the typical style of imperative programming.

2.2 Functional or Declarative Programming

Functional Programming is a different style of programming where in you would just be declarative of saying ONLY what to do and NEVER saying How to do, while leaving those internals to the underlying Programming Language itself that supports this paradigm. It will be easy and trouble-free for programmers thereby having a much cleaner and concise code.

One of the significant advantages of such style of programming is you would never need to worry about the internal intricacies thereby leaving the trouble of maintaining the flag/temporary variables, which would indirectly create any adverse effects that would affect the overall execution of the program elsewhere. Moreover, because there is no State Change, it offers various different advantages for effective and easy Unit Testing, Concurrent Programming etc., as they would be impacted if there is a global variable which could get changed by many different methods.

Languages like Ruby, Scala supports multiple programming paradigms like Object Oriented, Functional etc., We will see the functional programming in Scala in this tutorial.

2.4 Functional Programming – Sample Code

Let us understand the same with an example. Let us write the same program in Scala to find the first Odd number in a list of Integers.

FindFirstOddNumber.scala

import scala.collection.immutable.List

object FindFirstOddNumber {
        def main(args: Array[String]): Unit = {
                var intList = List(2,4,5,6,7)
                println(intList)
                var firstOddNumber = intList.filter(x => x%2==1).head
                println(firstOddNumber)
        }
}

Let us see the output of the above program.

C:\User\scalaPgms\> scalac FindFirstOddNumber.scala

C:\User\scalaPgms\> scala FindFirstOddNumber
List(2, 4, 5, 6, 7)
5

The first step was compiling the scala program using scalac executable. Has there been any errors, it would have been printed in the console. An absence of the message while invoking the scalc means the Scala source code was compiled successfully.

Next, the program was executed using the scala executable. As expected, the program first printed the input list of Integers an then printed the first odd number 5 and exited, which is nothing different from the previous version of Java program.

However, if you look inside the main method, we did not have any of the temporary flag variable to control to the loop iteration, or a temporary variable to hold each element in a collection (list) every time when the loop is iterated. This way, we achieve the immutability or the no state change, thereby leaving all the internal implementation details to the Programming language, here in our case scala itself. In essence, we did ONLY say what to do but NOT how to do.

3. What is a Function Vs Method

A function or a method is an reusable piece of executable code which has a name and a list of parameters (or arguments) that it requires to do its work and a return type indicating the type of value it could return. In Scala, if a function returns nothing it is called as an Unit, which is called as void in other programming languages like C, C++ and Java.

Though the terms function and method can be interchangeably used in most places, there are subtle differences between both of them in Scala. You may please read this link for the differences. The rest of the useful and relevant links are available at the References section at the bottom. The primary difference between a function and a method is the a function literal can be assigned as a value to a variable whereas a method cannot be.

Let us see a sample method in Scala using the Scala REPL (Read-Evaluate-Print-Loop) interpreter.

scala> def sayHello(name: String) = {
     |           "Hello " + name
     | }
sayHello: (name: String)String

The above code declared and defined a method named sayHello with the help of a keyword def along with the set of paranthesis ( for opening and ) for closing. The parantheses are the demarcating points for the input arguments to the functions, which are also called as parameters. In this sayHello function, we had defined a single parameter called name which is of type String both of them separated by a semicolon (:) – both within the paranthesis. An equals (=) sign as a reserved word (keyword) used to separate the method name with parameters from the method body (that contains the actual code to be executed), surrounded with a pair of curly braces { and }.

As you can easily infer from the name of the method, this method will print the name (which is passed an input to the function) along with “Hello” as a prefix. The function definition spawns across three lines where as you can see a vertical bar on the left side appearing from line 2 onwards, as soon as you press enter after completing the text from 1st line. The vertical bar continues to appear until you type the closing curly brace } which is the logical ending of a code / method block. There is no need of an explicit return statement at the end of the method as the last line of executable statement will be inferred as the return value automatically by Scala.

After the method definition is completed, scala REPL gives us back the short from of the method signature in one line – which is sayHello: (name:String) String. This indicates that a method named sayHello defined with a single parameter of type String and the method returns a value of type String (which is the last line of the method – which is “Hello” prefixed with the ‘name’ input parameter).

Let us write the same ‘sayHello’ as a function in Scala below.

scala> val sayHello = (name:String) => {
     |     "Hello " + name
     | }
sayHello: String => String = <function1>

Here a function literal (anonymous function – as it does not have any name) is assigned to the variable name sayHello with a parameter of type String. The other difference here is we have used the symbol => (an equals sign with a right arrow key together) to separate the function name and the body.

The Scala REPL interpreter gave us back the function signature in one line as follows. sayHello: String => String = <function1> – meaning a function literal has been defined with an input parameter of type String and a return value of type String. It is of type <function1> – meaning this is an instance of Scala’s one of the many implicit function objects that takes one (1) input argument.

Let us try executing this function or a method in the Scala REPL. The execution is the same for both method and a function.

scala> sayHello("Raghavan")
res22: String = Hello Raghavan

scala> sayHello("Scala")
res23: String = Hello Scala

scala> sayHello(" ")
res24: String = "Hello  "

Because the function literal is assigned to a variable named ‘sayHello’ that takes a single input parameter, the execution will not be any different for each other.

As you can see, we had invoked the function ‘sayHello’ with different arguments and the Scala REPL gave us back the results instantly which are very much self explanatory. The prefix res22: is the temporary variable Scala REPL stores as and when it keeps calculating expressions. It would be incremental for every expression being typed in the REPL interpreter. Like in our case, it is res22 to res24 – meaning the 22nd to 24th buffered results of evaluating expressions in the current session of Scala REPL interpreter.

4. Functional Programing Concepts

Now that we have a good understanding on the fundamentals of Functional Programming, let us see some of the core principles or concepts of the same, which are the essential building blocks of any language that supports the functional programming.

4.1. Immutability

The term immutability refers to the ability to preserve the value of the variables unchanged. Mutable means changeable and immutable means the opposite.

In Functional Programming, the immutability is the key factor with which a function is guaranteed to produce the same output for the same input, invariably how many ever times it is invoked. The reason being it does not mutate or change any of the values other than the input arguments like global state – a variable that is declared outside the routine or function which may cause some side effects.

In our previous example, the invocation of the function sayHello with the same input Raghavan will always yield the same output – Hello, Raghavan across any number of invocations.

4.2. Side Effects

The side effects are the changes if any happening other than what was intended to happen as a result of executing a function or a method.

For example, you may have a method accepting an input argument and producing a resultant value. However the output will NOT be only dependent on the input value but some other variable/value other than the input argument, hence the result might certainly vary for subsequent invocations in case the other non-input variable’s value gets changed from time to time. This is actually called as a side effect, as this is something not expected out of the method execution and it is not depending on the input arugment.

Let us see an example code to understand the same.

SideEffect.scala

object SideEffect {

        var count = 0;

        def main(args: Array[String]):Unit = {
                val x = 1

                for(i <- 1 to 3) {
                        def modified = modifyValue(x)
                        println(s"Input : $x, Modified : $modified")
                }

                println("------------")

                for(i <- 1 to 3) {
                        def incremented = plusOne(x)
                        println(s"Input : $x, Incremented : $incremented")
                }
        }

        def modifyValue(x:Int):Int = {
                count = count + 1
                x + count
        }

        def plusOne(x:Int):Int = {
                x + 1
        }
}

The above program has an instance variable called ‘count’ and a method called modifyValue which accepts an integer value as an input argument and it returns an integer. This modifyValue method is called three times in a for loop with the same input value 1.

This code has also got another method called plusOne which accepts one input argument and modifies ONLY the input argument before producing the result.

Let us see the output of the above program.

C:\Users\scalaPgms\> scalac SideEffect.scala

C:\Users\scalaPgms\> scala SideEffect
Input : 1, Modified : 2
Input : 1, Modified : 3
Input : 1, Modified : 4
------------
Input : 1, Incremented : 2
Input : 1, Incremented : 2
Input : 1, Incremented : 2

As you see, the output varies each time as the modified value is different for every invocation (or execution), eventhough the modifyValue() method is invoked with the same input value 1 at all the times. The reason being, the output of the method modifyValue() is not just on the input argument passed but also based on the other variable called ‘count’ which is an instance level variable.

From the main() method, this modifyValue() is called 3 times with the same input value (1) but the output is different everytime because the instance variable count is increased within the modifyValue() method everytime it is invoked. Hence, this method modifyValue() is proven to have a side effect, which is something else other than the intended purpose of method execution (which is incrementing the count variable’s value thereby affecting the result of method execution eventhough the same input is passed for every invocation).

However, if you look at the output of plusOne method, the output has never changed for all the invocations. It is because the plusOne() method was depending only on the input argument for the output. Hence the result was the same thereby proving that this method does not have any side effects.

If a method is relying on or doing some other operation other than the input arguments of its own, it is said to have a side effect.

4.3. Referential Transparency

The term Referential Transparency means if an expression or a function execution will always produce the same result for the same input, the expression can be replaced with its value (final evaluated value) in place of the expression wherever it is used in a program, provided there is no change in the result of execution of an expression or a function. In case there is a change happens during the replacement of value for the expression, it is not referentially transparent. You can’t safely or transparently reference the expression with its value.

Let us look at the same with an example. First let us see a program where we can safely do or have a referential transparency by replacing the expression or variable with its value in place.

ReferentialTransparencyPerfect.scala

object ReferentialTransparencyPerfect {
        def main(args:Array[String]):Unit = {
                println("")
                println("----------- String Reverse --------------- ")
                stringReverse()
                println("")
                println(" ======= Referential Transparency ========")
                refTransparencyString()
                println("")
        }

        def stringReverse() = {
                val x = "Hello, World"
                println(s"Input : $x")
                val r1 = x.reverse
                println(s"Reverse - variable value r1 : $r1")
                val r2 = x.reverse
                println(s"Reverse - variable value r2 : $r2")
        }

        def refTransparencyString() = {
                val r1 = "Hello, World".reverse
                println(s"Reverse - direct value r1 : $r1")
                val r2 = "Hello, World".reverse
                println(s"Reverse - direct value r2 : $r2")
        }
}

The above scala program has two different methods – stringReverse() and refTransparencyString(), in addition to the typical main() method. The stringReverse() method defines one value Hello, World to a variable x. It then invokes the reverse() method on the variable x by obtaining the string reversal and assigns this to a variable r1 and prints the same. It does the same thing again for another variable r2 and prints the value of r2.

The next method refTransparencyString does the same thing but with a difference. Rather than assigning the input String to a variable x and then using the variable’s value for subsequent reverse operations for assigning to r1 and r2, this method directly places the input string Hello, World in place of ‘x’ in both r1 and r2’s assignment.

Let us see the output of the above program.

C:\Users\scalaPgms\> scalac ReferentialTransparencyPerfect.scala

C:\Users\scalaPgms\> scala ReferentialTransparencyPerfect

----------- String Reverse ---------------
Input : Hello, World
Reverse - variable value r1 : dlroW ,olleH
Reverse - variable value r2 : dlroW ,olleH

 ======= Referential Transparency ========
Reverse - direct value r1 : dlroW ,olleH
Reverse - direct value r2 : dlroW ,olleH

As you see, the output is same for executing both the stringReverse() and refTransparencyString() methods. Since the transformation does not affect the outcome, we can say that x is referentially transparent. Same way, r1 and r2 are also referentially transparent, throughout the program. In case these variables are present in many places of the program, we can safely replace the variable with the value as this will not affect the output of the program.

Let us now see another program where we cannot safely do or have a referential transparency by replacing the expression or variable with its value in place.

ReferentialTransparencyBroken.scala

object ReferentialTransparencyBroken {                                          
        def main(args:Array[String]):Unit = {                                   
                println("")                                                     
                println(" ------------ StringBuffer Append --------------- ")   
                strBufferAppend()                                              
                println("")                                                     
                println(" ======== Referential Transparency (broken) ======= ") 
                refTransparencyStrBuffer()                                      
                println("")                                                     
        }                                                                       
                                                                                
        def strBufferAppend() = {                                              
                val x = new StringBuffer("Hello")                               
                val y = x.append(", World")                                     
                val r1 = y.toString                                             
                println(s"StrBuffer appended variable value - r1 : $r1")        
                val r2 = y.toString                                             
                println(s"StrBuffer appended variable value - r2 : $r2")        
        }                                                                       
                                                                                
        def refTransparencyStrBuffer() = {                                      
                val x = new StringBuffer("Hello")                         
                val r1 = x.append(", World").toString                           
                println(s"StrBuffer appended direct value - r1 : $r1")          
                val r2 = x.append(", World").toString                           
                println(s"StrBuffer appended direct value - r2 : $r2")          
        }                                                                       
}                                                                               

The above scala program has two different methods – strBufferAppend() and refTransparencyStrBuffer(), in addition to the typical main() method. The strBufferAppend() method defines one value Hello to a variable x as an initial value while instantiating a StringBuffer instance. It then appends another string ", World" with the existing value of x and assigns it to a new varaible y. It then invokes the toString() on the variable y, which will return the value of ‘y’ that is assigned to the variable r1 which gets printed on the next line. Similarly it invokes the toString() on ‘y’ and assigns to another variable r2 which gets printed in the subsequent line.

The next method refTransparencyStrBuffer does the same thing but with a difference like the previous program. Rather than assigning the input String to a variable y and then using the variable’s value for subsequent toString() operations for assigning to r1 and r2, this method directly places the value of ‘y’ which is x.append(", World") in place of ‘y’ in both r1 and r2’s assignment.

Let us see the output of the above program.

C:\Users\scalaPgms\> scalac ReferentialTransparencyBroken.scala

C:\Users\scalaPgms\> scala ReferentialTransparencyBroken

 ------------ StringBuffer Append ---------------
StrBuffer appended variable value - r1 : Hello, World
StrBuffer appended variable value - r2 : Hello, World

 ======== Referential Transparency (broken) =======
StrBuffer appended direct value - r1 : Hello, World
StrBuffer appended direct value - r2 : Hello, World, World

As you see, the strBufferAppend method did not have anything different as we were using the value of a variable. However the output of refTransparencyStrBuffer was different because we had replaced the value of ‘y’ – which is x.append(", World") in place of ‘y’ during the assignment of r1 and r2.

If you observe closely, at first when the value x.append(", World") was assigned to r1, the value of r1 was "Hello, World" properly. However the value of x was indirectly changed to “Hello, World” as opposed to the original “Hello” due to the append() method. When the same replacement happens again for ‘r2’, the value x.append(", World") will be evaluated to "Hello, World".append(", World") and hence the result was produced as "Hello, World, World". Hence, we cannot say that the append method is referentially transparent.

4.4. Pure and Impure functions

Having understood about the immutability, we can get this terminology in an easy manner.

A function is said to be pure if it always guarantees to produce the same results for the same input without causing any side effects.

It is more of a mathematical function sin(x) where this function will always give the same output for the same x value, no matter how many times we invoke. This forms the very basics of Functional Programming. The sin(x) is a pure function due to the nature of its implementation.

We can say that from the previous examples, plusOne() method in SideEffect.scala is a pure function. The same way, the append() method of StringBuilder is an impure function as demonstrated in the ReferentialTransparencyBroken.scala class.

4.5. Higher Order Functions

In Functional Programming world, the Higher Order Functions (HOF) are the functions which receive a function as one of the input parameters OR a function which returns a function as a result.

In case of a function being passed an argument, it will help that passed function to be used in place of a variable inside the method, which the programmer can conveniently replace on demand without any changes on the method.

Let us see an example program to understand the same.

HigherOrderFunctions.scala

object HigherOrderFunctions {
        def main(args:Array[String]):Unit = {
                val add = (x:Int, y:Int) => { x + y }
                operation(add)

                val subtract = (x:Int, y:Int) => { x - y }
                operation(subtract)

                val multiply = (x:Int, y:Int) => { x * y }
                operation(multiply)
        }

        def operation(f:(Int,Int) => Int) {
           println(f(5,5))
        }
}

The above Scala program has a function named operation that takes a function as an input parameter/argument which is f:(Int,Int) => Int – indicating that the function f will accept two integer parameters and will return an integer value. The operation method will indeed invoke the passed function f with the values 5, 5 for the f to work.

We had defined 3 different methods add, subtract and multiply where each of them is a separate function taking two integer arguments and returning the result out of the corresponding mathematical operation on the two input parameters received as ‘x’ and ‘y’.

The main() method invokes the function operation three times subsequently by passing each of the mathematical functions one at a time.

The output of the program is given as below.

C:\Users\scalaPgms\> scala HigherOrderFunctions
10
0
25

As you see, the main() method invoked the 3 different mathematical functions – add, subtract, multiply. The operation method invoked the corresponding function which is received as an input with the input values ‘5’, and ‘5’ for all the functions. Hence we see the output as 10 for ‘add’, 0 for ‘subtract’ and 25 for ‘multiply’.

We can call the method operation as a Higher Order Function (HOF) since it works with another function passed as an argument. Similarly a function can also return a function as a result.

5. Example Program – SumOfSquaresOfOdd

Let us combine all our learning and put into practice by a different program. We will see the same program in both imperative and function ways in Java and Scala respectively.

5.1 SumOfSquaresofOdd – Imperative Way (Java)

The program is to find the sum of square of the odd numbers in a list passed and print the sum in the console. Let us first see the Imperative way and then look at the functional way, as to how simple and easy Scala offers the API methods for us to easily do with FP (Functional Programming).

SumOfSquaresOfOdd.java

import java.util.*;

public class SumOfSquaresOfOdd
{
    public static void main(String... args)
    {
        List intList = new ArrayList();

        for(int i = 1; i <= 5; i++) {
                intList.add(i);
        }

        System.out.println("intList - Initial : " + intList);

        List oddNoList = new ArrayList();

        for(int i = 0; i < intList.size(); i++) {
                if(intList.get(i)%2==1) {
                        oddNoList.add(intList.get(i));
                }
        }

        System.out.println("oddNoList : " + oddNoList);

        List squareList  = new  ArrayList();

        for(int i=0; i < oddNoList.size(); i++) {
                squareList.add(oddNoList.get(i) * oddNoList.get(i));
        }

        System.out.println("squareList : " + squareList);

        int sum = 0;
        for(Integer i : squareList) {
                sum += i;
        }

        System.out.println("Sum : " + sum);
    }
}

The above program has a main() method that has the detailed steps indicating How to do the problem solving step by step, wherein defining an intList having a list of Integers, preparing a oddNoList by looping through the input list intList and then preparing another list called squareList by iterating the oddNoList for finding the square value of each number, and finally iterating the squareList to iterate each element to calculate the sum of each element in the list.

For each iteration, we had used a temporary varaible i, which is used as a loop control variable that keeps getting a new value for every iteration. This way, the program tends to be more verbose, having lot of potential areas of code break due to so many vulnerabilities along the way.

The output of the above program is given below.

C:\Users\javaPgms\> javac SumOfSquaresOfOdd.java

C:\Users\javaPgms\> java SumOfSquaresOfOdd
intList - Initial : [1, 2, 3, 4, 5]
oddNoList : [1, 3, 5]
squareList : [1, 9, 25]
Sum : 35

The output of executing the above Java program is self explanatory as it prints out each list for every step of execution, so as to give the visual clue to the readers as to how the program is evolving to reach the final target.

5.2 SumOfSquaresOfOdd – Functional Way (Scala)

Let us now see the same program in Scala, as to how easy and simple it is to achieve without any of the overheads or the verbosities. They are also called as ‘ceremonies’.

SumOfSquaresOfOdd.scala

import scala.collection.immutable.List

object SumOfSquaresOfOdd
{
        def main(args:Array[String]):Unit =
        {
                var intList = List(1,2,3,4,5)
                def sum = intList.filter(x => x % 2 ==1).map(x => x * x).reduce((x,y) => x+y)
                println(sum)
        }
}

As you see the same program has become so concise in Scala as we have a simple and easy API methods avaiable in Scala. We use the filter method to pick up the odd numbers, map method to iterate each element of the list/collection by applying a square of each value, reduce method to walk through each element in a collection to sum them up all.

At the outset, we never say How to do the operation rather we just say what to do in a functional or declarative way, leaving aside the implementation to Scala itself.

The output of the above program is given below.

C:\Users\scalaPgms\> scalac SumOfSquaresOfOdd.scala

C:\Users\scalaPgms\> scala SumOfSquaresOfOdd
35

The output is pretty straight forward and self explanatory. The output contains just the final sum without any of the intermediate verbosity, since we had obviously avoided all the intermediate implementation details in our code.

6. Advantages of Functional Programming

The functional programming due to its nature of favoring and honoring the core concepts such as Higher Order Functions, pure functions, immutability, referential transparency – offers several advantages – of which few of them are listed below.

Clean and Conside code – due to the several built in API methods offerred by Scala, the code becomes very clean and concise.

Modurality and better reusability – Functional programming forces large problems to be broken down into smaller instances of the same problem to be solved. This way, the code will become more modular. Moreover, we can make the methods reusable as we could have several common helper or utility methods to be used across different layers of the application.

Reduced Coupling – Coupling is the amount of dependency between modules in a Program. Because the functional program will have few higher order and pure functions which are completely independent of each other with no side effect on global variables, the coupling is greatly reduced.

Better and Efficient Unit Testing – as there is no immutability and functions are mostly pure, it is easy to do an efficien Unit Testing, since we don’t need to really bother about any side effects like global state change.

Better Concurrent Programming – as there is no global state change etc., the concurrent programming becomes very easy. Scala as such has got several built in ways to efficiently handle the concurrent / multi-threaded programming.

7. Conclusion

Hope this tutorial gave you a good understanding on the Functional Programming in Scala. Please check out the various given across the different sections including the Reference section below for a better understanding of the FP concepts and try to practice more with different programs in a functional way.

8. References

You may please refer the following URLs for further reading.

  1. Scala Tutorial for Beginners – JCG
  2. Functional Programming – Wikipedia
  3. Referential Transparency – Wikipedia
  4. Side Effect – Wikipedia
  5. Pure Function – Wikipedia
  6. Functional Programming Basics
  7. Why Functional Programming
  8. Functional Programming – C2 wiki
  9. Functional Programming vs. Imperative Programming
  10. What is Functional Programming
  11. Intro to FP with Scala
  12. Scala – Functions Vs Methods

9. Download the Source Code

All the examples in this article are tested in the Command Prompt / Shell against Scala Version 2.11.7.

Download
You can download the full source code of this example here: Functional Programming in Scala.
(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Haaris Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Haaris
Guest
Haaris

Thank you so much! This article helped me a lot with understanding functional programming.