{"id":36937,"date":"2016-05-09T11:00:24","date_gmt":"2016-05-09T08:00:24","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=36937"},"modified":"2019-03-29T14:05:56","modified_gmt":"2019-03-29T12:05:56","slug":"functional-programming-scala","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/","title":{"rendered":"Functional Programming in Scala"},"content":{"rendered":"<p>In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language.<\/p>\n<p>According to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Functional_programming\">Wikipedia<\/a>, the definition of Functional Programming is as follows.<\/p>\n<blockquote>\n<p>In computer science, functional programming is a programming paradigm &#8211; a style of building the structure and elements of computer programs\u2014that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.<\/p>\n<\/blockquote>\n<p><b>Pre-requisite: <\/b>The readers are expected to know the basics of Java and Scala Programming.<\/p>\n<p>The following table shows an overview of the entire article:\n<\/p>\n<div class=\"toc\">\n<h3>Table of Contents<\/h3>\n<dl>\n<dt><a href=\"#env\">1. Environment<\/a><\/dt>\n<dt><a href=\"#prog-paradigm\">2. Two different but major Programming Styles<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#prog-paradigm-imperative\">2.1 Imperative or Procedural Programming<\/a><\/dt>\n<dt><a href=\"#prog-paradigm-imperative-code\">2.2 Imperative Programming &#8211; Sample Code<\/a><\/dt>\n<dt><a href=\"#prog-paradigm-fp\">2.3 Functional or Declarative Programming<\/a><\/dt>\n<dt><a href=\"#prog-paradigm-fp-code\">2.4 Functional Programming &#8211; Sample Code<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#function-vs-method\">3. What is a Function Vs Method<\/a><\/dt>\n<dt><a href=\"#fp-concepts\">4. Functional Programing Concepts<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#fp-concepts-immutability\">4.1. Immutability<\/a><\/dt>\n<dt><a href=\"#fp-concepts-side-effects\">4.2. Side Effects<\/a><\/dt>\n<dt><a href=\"#fp-concepts-ref-transparency\">4.3. Referential Transparency<\/a><\/dt>\n<dt><a href=\"#fp-concepts-pure-impure-fns\">4.4. Pure and Impure functions<\/a><\/dt>\n<dt><a href=\"#fp-concepts-higer-order-fns\">4.5. Higher Order Functions<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#example\">5. Example Program &#8211; SumOfSquaresOfOdd<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#example-imper\">5.1 SumOfSquaresofOdd &#8211; Imperative Way (Java)<\/a><\/dt>\n<dt><a href=\"#example-fp\">5.2 SumOfSquaresOfOdd &#8211; Functional Way (Scala)<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#adv-fp\">6. Advantages of Functional Programming<\/a><\/dt>\n<dt><a href=\"#conclusion\">7. Conclusion<\/a><\/dt>\n<dt><a href=\"#ref\">8. References<\/a><\/dt>\n<dt><a href=\"#download\">9. Download the Source Code<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"env\"><\/a>1. Environment<\/h2>\n<p>The examples in this article are executed in the <i>Command Prompt \/ Shell<\/i> with the Scala Interpreter. But they are guaranteed to work with any of the IDEs (like <i>Eclipse &#8211; Scala IDE, IntelliJ IDEA etc.,<\/i>) through the respective plugins. The examples are executed with the <strong>Scala Version: 2.11.7 in Windows 7<\/strong>.<\/p>\n<p>You may refer to my previous tutorial <a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/scala-tutorial-beginners\">here<\/a> on how to install Scala, if you are a beginner with Scala.<\/p>\n<h2><a name=\"prog-paradigm\"><\/a>2. Two different but major Programming Styles<\/h2>\n<p>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.<\/p>\n<p>Though FP (Functional Programming) appears to be a new buzzword, it had been in the industry since many decades right from <code>Lisp<\/code>, <code>Erlang<\/code> though it was originated from <code>Lambda Calculus<\/code>. However in the recent past this style has been acquired in the newly evolved Programming languages like Scala, Ruby, Clojure etc.,<\/p>\n<h3><a name=\"prog-paradigm-imperative\"><\/a>2.1 Imperative or Procedural Programming<\/h3>\n<p>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 <b>How to do<\/b> alongside <i>what to do<\/i>.<\/p>\n<p>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 <code>for<\/code>, <code>while<\/code> and <code>do-while<\/code> etc., and within these looping structures a temporary variable (called as a <code>flag<\/code> or an <code>interim variable<\/code> depending on the context) which gets changed for every iteration of a collection in a loop. This is actually called as a <b>state change<\/b> of a variable which can be either local to a method or global to a class in which the method is defined.<\/p>\n<p>Moreover, the actual code involved in doing the work will be detailing every minute step of a problem being solved.<\/p>\n<h3><a name=\"prog-paradigm-imperative-code\"><\/a>2.2 Imperative Programming &#8211; Sample Code<\/h3>\n<p>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.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>FindFirstOddNumber.java<\/em><\/span><\/p>\n<pre class=\"brush:java;\">import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class FindFirstOddNumber\n{\n  public static void main(String... args)\n  {\n    \/\/ Arrays.asList() will return an ArrayList from the list of numbers\n    List intList = Arrays.asList(2,4,5,6,7);\n  \n    System.out.println(\"Input List : \" + intList);\n    \n    boolean found = false;\n\n    for(int i : intList)\n    {\n      if(i%2==1)\n      {\n        System.out.println(\"Found the first odd number - \" + i);\n        found = true;\n        break;\n      }\n    }\n\n    if(!found)\n    {\n      System.out.println(\"No odd number present in the list\");\n    }\n  }\n}                                                                                        \n<\/pre>\n<p>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.<\/p>\n<p>Let us see the output of the above program.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\javaPgms\\&gt; java FindFirstOddNumber\nInput List : [2, 4, 5, 6, 7]\nFound the first odd number - 5\n<\/pre>\n<p>As expected, the program first printed the input list of Integers and then printed the first odd number <code>5<\/code> and exited.<\/p>\n<p>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 <code>found<\/code> 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 <code>i<\/code> which is used inside an enhanced for loop (it is called as <code>foreach<\/code> loop) where the value of <code>i<\/code> is changed with the new value (element at the current index) for every iteration.<\/p>\n<p>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 <b>how<\/b> this program will work. This is the typical style of <code>imperative<\/code> programming.<\/p>\n<h3><a name=\"prog-paradigm-fp\"><\/a>2.2 Functional or Declarative Programming<\/h3>\n<p>Functional Programming is a different style of programming where in you would just be declarative of saying <b>ONLY<\/b> <i>what to do<\/i> and <b>NEVER<\/b> saying <i>How to do<\/i>, 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.<\/p>\n<p>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.<\/p>\n<p>Languages like <code>Ruby<\/code>, <code>Scala<\/code> supports <b>multiple programming paradigms<\/b> like <i>Object Oriented, Functional<\/i> etc., We will see the functional programming in Scala in this tutorial.<\/p>\n<h3><a name=\"prog-paradigm-fp-code\"><\/a>2.4 Functional Programming &#8211; Sample Code<\/h3>\n<p>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.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>FindFirstOddNumber.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">import scala.collection.immutable.List\n\nobject FindFirstOddNumber {\n        def main(args: Array[String]): Unit = {\n                var intList = List(2,4,5,6,7)\n                println(intList)\n                var firstOddNumber = intList.filter(x =&gt; x%2==1).head\n                println(firstOddNumber)\n        }\n}\n<\/pre>\n<p>Let us see the output of the above program.<\/p>\n<pre class=\"brush:java;\">C:\\User\\scalaPgms\\&gt; scalac FindFirstOddNumber.scala\n\nC:\\User\\scalaPgms\\&gt; scala FindFirstOddNumber\nList(2, 4, 5, 6, 7)\n5\n<\/pre>\n<p>The first step was compiling the scala program using <code>scalac<\/code> executable. Has there been any errors, it would have been printed in the console. An absence of the message while invoking the <code>scalc<\/code> means the Scala source code was compiled successfully.<\/p>\n<p>Next, the program was executed using the <code>scala<\/code> executable. As expected, the program first printed the input list of Integers an then printed the first odd number <code>5<\/code> and exited, which is nothing different from the previous version of Java program.<\/p>\n<p>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 <code>immutability<\/code> or the <code>no state change<\/code>, thereby leaving all the internal implementation details to the Programming language, here in our case <code>scala<\/code> itself. In essence, we did ONLY say <i>what to do<\/i> but <b>NOT<\/b> <i>how to do<\/i>.<\/p>\n<h2><a name=\"function-vs-method\"><\/a>3. What is a Function Vs Method<\/h2>\n<p>A <code>function<\/code> or a <code>method<\/code> 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 <code>Unit<\/code>, which is called as <code>void<\/code> in other programming languages like <code>C<\/code>, <code>C++<\/code> and <code>Java<\/code>.<\/p>\n<blockquote>\n<p>Though the terms <code>function<\/code> and <code>method<\/code> can be interchangeably used in most places, there are subtle differences between both of them in Scala. You may please read this <a href=\"http:\/\/jim-mcbeath.blogspot.in\/2009\/05\/scala-functions-vs-methods.html\">link<\/a> for the differences. The rest of the useful and relevant links are available at the <b><a href=\"#ref\">References<\/a><\/b> 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.<\/p>\n<\/blockquote>\n<p>Let us see a sample method in Scala using the Scala <code>REPL<\/code> (Read-Evaluate-Print-Loop) interpreter.<\/p>\n<pre class=\"brush:java;\">scala&gt; def sayHello(name: String) = {\n     |           \"Hello \" + name\n     | }\nsayHello: (name: String)String\n<\/pre>\n<p>The above code declared and defined a method named <code>sayHello<\/code> with the help of a keyword <code>def<\/code> along with the set of paranthesis <code>(<\/code> for opening and <code>)<\/code> for closing. The parantheses are the demarcating points for the input arguments to the functions, which are also called as <code>parameters<\/code>. In this <code>sayHello<\/code> function, we had defined a single parameter called <code>name<\/code> which is of type <code>String<\/code> both of them separated by a semicolon (:) &#8211; both within the paranthesis. An <code>equals (=) <\/code> 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 <code>{<\/code> and <code>}<\/code>.<\/p>\n<p>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 &#8220;Hello&#8221; 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 <code>}<\/code> which is the logical ending of a code \/ method block. There is no need of an <code>explicit<\/code> 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.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<blockquote>\n<p>After the method definition is completed, scala REPL gives us back the short from of the method signature in one line &#8211; which is <b><code>sayHello: (name:String) String<\/code><\/b>. This indicates that <i><u><\/u>a method named <code>sayHello<\/code> defined with a single parameter of type <code>String<\/code> and the method returns a value of type <code>String<\/code> (which is the last line of the method &#8211; which is &#8220;Hello&#8221; prefixed with the &#8216;name&#8217; input parameter).<\/i><\/p>\n<\/blockquote>\n<p>Let us write the same &#8216;sayHello&#8217; as a function in Scala below.<\/p>\n<pre class=\"brush:java;\">scala&gt; val sayHello = (name:String) =&gt; {\n     |     \"Hello \" + name\n     | }\nsayHello: String =&gt; String = &lt;function1&gt;\n<\/pre>\n<p>Here a function literal (anonymous function &#8211; as it does not have any name) is assigned to the <b>variable<\/b> name <code>sayHello<\/code> with a parameter of type <code>String<\/code>. The other difference here is we have used the symbol <code>=&gt; (an equals sign with a right arrow key together)<\/code> to separate the function name and the body.<\/p>\n<blockquote>\n<p>The Scala REPL interpreter gave us back the function signature in one line as follows. <code><b>sayHello: String =&gt; String = &lt;function1&gt;<\/b><\/code> &#8211; meaning <i>a function literal has been defined with an input parameter of type <code>String<\/code> and a return value of type <code>String<\/code>. It is of type <code>&lt;function<b>1<\/b>&gt;<\/code> &#8211; meaning this is an instance of Scala&#8217;s one of the many <b>implicit function objects that takes one (1) input argument.<\/b><\/i><\/p>\n<\/blockquote>\n<p>Let us try executing this function or a method in the Scala REPL. The execution is the same for both method and a function.<\/p>\n<pre class=\"brush:java;\">scala&gt; sayHello(\"Raghavan\")\nres22: String = Hello Raghavan\n\nscala&gt; sayHello(\"Scala\")\nres23: String = Hello Scala\n\nscala&gt; sayHello(\" \")\nres24: String = \"Hello  \"\n<\/pre>\n<p>Because the function literal is assigned to a variable named &#8216;sayHello&#8217; that takes a single input parameter, the execution will not be any different for each other.<\/p>\n<p>As you can see, we had invoked the function &#8216;sayHello&#8217; with different arguments and the Scala REPL gave us back the results instantly which are very much self explanatory. The prefix <code>res22:<\/code> 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 <code>res22<\/code> to <code>res24<\/code> &#8211; meaning the 22nd to 24th buffered results of evaluating expressions in the current session of Scala REPL interpreter.<\/p>\n<h2><a name=\"fp-concepts\"><\/a>4. Functional Programing Concepts<\/h2>\n<p>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.<\/p>\n<h3><a name=\"fp-concepts-immutability\"><\/a>4.1. Immutability<\/h3>\n<p>The term <code>immutability<\/code> refers to the ability to preserve the value of the variables unchanged. <code>Mutable<\/code> means <code>changeable<\/code> and <code>immutable<\/code> means the opposite.<\/p>\n<p>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 &#8211; a variable that is declared outside the routine or function which may cause some side effects.<\/p>\n<p>In our previous example, the invocation of the function <code>sayHello<\/code> with the same input <code>Raghavan<\/code> will <b>always<\/b> yield the same output &#8211; <code>Hello, Raghavan<\/code> across any number of invocations.<\/p>\n<h3><a name=\"fp-concepts-side-effects\"><\/a>4.2. Side Effects<\/h3>\n<p>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.<\/p>\n<p>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&#8217;s value gets changed from time to time. This is actually called as a <code>side effect<\/code>, as this is something not expected out of the method execution and it is not depending on the input arugment.<\/p>\n<p>Let us see an example code to understand the same.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>SideEffect.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">object SideEffect {\n\n        var count = 0;\n\n        def main(args: Array[String]):Unit = {\n                val x = 1\n\n                for(i &lt;- 1 to 3) {\n                        def modified = modifyValue(x)\n                        println(s\"Input : $x, Modified : $modified\")\n                }\n\n                println(\"------------\")\n\n                for(i &lt;- 1 to 3) {\n                        def incremented = plusOne(x)\n                        println(s\"Input : $x, Incremented : $incremented\")\n                }\n        }\n\n        def modifyValue(x:Int):Int = {\n                count = count + 1\n                x + count\n        }\n\n        def plusOne(x:Int):Int = {\n                x + 1\n        }\n}\n<\/pre>\n<p>The above program has an instance variable called &#8216;count&#8217; and a method called <code>modifyValue<\/code> which accepts an integer value as an input argument and it returns an integer. This <code>modifyValue<\/code> method is called three times in a for loop with the same input value <code>1<\/code>.<\/p>\n<p>This code has also got another method called <code>plusOne<\/code> which accepts one input argument and <b>modifies ONLY the input argument<\/b> before producing the result.<\/p>\n<p>Let us see the output of the above program.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\scalaPgms\\&gt; scalac SideEffect.scala\n\nC:\\Users\\scalaPgms\\&gt; scala SideEffect\nInput : 1, Modified : 2\nInput : 1, Modified : 3\nInput : 1, Modified : 4\n------------\nInput : 1, Incremented : 2\nInput : 1, Incremented : 2\nInput : 1, Incremented : 2\n<\/pre>\n<p>As you see, the output varies each time as the modified value is different for every invocation (or execution), eventhough the <code>modifyValue()<\/code> method is invoked with the same input value <code>1<\/code> 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 &#8216;count&#8217; which is an instance level variable.<\/p>\n<p>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&#8217;s value thereby affecting the result of method execution eventhough the same input is passed for every invocation).<\/p>\n<p>However, if you look at the output of <code>plusOne<\/code> method, the output has never changed for all the invocations. It is because the <code>plusOne()<\/code> 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.<\/p>\n<blockquote>\n<p>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 <code>side effect<\/code>.<\/p>\n<\/blockquote>\n<h3><a name=\"fp-concepts-ref-transparency\"><\/a>4.3. Referential Transparency<\/h3>\n<p>The term <code>Referential Transparency<\/code> 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&#8217;t safely or transparently reference the expression with its value.<\/p>\n<p>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.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>ReferentialTransparencyPerfect.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">object ReferentialTransparencyPerfect {\n        def main(args:Array[String]):Unit = {\n                println(\"\")\n                println(\"----------- String Reverse --------------- \")\n                stringReverse()\n                println(\"\")\n                println(\" ======= Referential Transparency ========\")\n                refTransparencyString()\n                println(\"\")\n        }\n\n        def stringReverse() = {\n                val x = \"Hello, World\"\n                println(s\"Input : $x\")\n                val r1 = x.reverse\n                println(s\"Reverse - variable value r1 : $r1\")\n                val r2 = x.reverse\n                println(s\"Reverse - variable value r2 : $r2\")\n        }\n\n        def refTransparencyString() = {\n                val r1 = \"Hello, World\".reverse\n                println(s\"Reverse - direct value r1 : $r1\")\n                val r2 = \"Hello, World\".reverse\n                println(s\"Reverse - direct value r2 : $r2\")\n        }\n}\n<\/pre>\n<p>The above scala program has two different methods &#8211; <code>stringReverse()<\/code> and <code>refTransparencyString()<\/code>, in addition to the typical <code>main()<\/code> method. The <code>stringReverse()<\/code> method defines one value <code>Hello, World<\/code> to a variable <code>x<\/code>. It then invokes the <code>reverse()<\/code> method on the variable x by obtaining the string reversal and assigns this to a variable <code>r1<\/code> and prints the same. It does the same thing again for another variable <code>r2<\/code> and prints the value of <code>r2<\/code>.<\/p>\n<p>The next method <code>refTransparencyString<\/code> does the same thing but with a difference. Rather than assigning the input String to a variable <code>x<\/code> and then using the variable&#8217;s value for subsequent <code>reverse<\/code> operations for assigning to <code>r1<\/code> and <code>r2<\/code>, this method directly places the input string <code>Hello, World<\/code> in place of &#8216;x&#8217; in both r1 and r2&#8217;s assignment.<\/p>\n<p>Let us see the output of the above program.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\scalaPgms\\&gt; scalac ReferentialTransparencyPerfect.scala\n\nC:\\Users\\scalaPgms\\&gt; scala ReferentialTransparencyPerfect\n\n----------- String Reverse ---------------\nInput : Hello, World\nReverse - variable value r1 : dlroW ,olleH\nReverse - variable value r2 : dlroW ,olleH\n\n ======= Referential Transparency ========\nReverse - direct value r1 : dlroW ,olleH\nReverse - direct value r2 : dlroW ,olleH\n\n<\/pre>\n<p>As you see, the output is same for executing both the <code>stringReverse()<\/code> and <code>refTransparencyString()<\/code> methods. Since the transformation does not affect the outcome, we can say that <code><b>x<\/b><\/code> is <i>referentially transparent<\/i>. Same way, <code>r1<\/code> and <code>r2<\/code> 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.<\/p>\n<p>Let us now see another program where we <i><b>cannot<\/b><\/i> safely do or have a referential transparency by replacing the expression or variable with its value in place.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>ReferentialTransparencyBroken.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">object ReferentialTransparencyBroken {                                          \n        def main(args:Array[String]):Unit = {                                   \n                println(\"\")                                                     \n                println(\" ------------ StringBuffer Append --------------- \")   \n                strBufferAppend()                                              \n                println(\"\")                                                     \n                println(\" ======== Referential Transparency (broken) ======= \") \n                refTransparencyStrBuffer()                                      \n                println(\"\")                                                     \n        }                                                                       \n                                                                                \n        def strBufferAppend() = {                                              \n                val x = new StringBuffer(\"Hello\")                               \n                val y = x.append(\", World\")                                     \n                val r1 = y.toString                                             \n                println(s\"StrBuffer appended variable value - r1 : $r1\")        \n                val r2 = y.toString                                             \n                println(s\"StrBuffer appended variable value - r2 : $r2\")        \n        }                                                                       \n                                                                                \n        def refTransparencyStrBuffer() = {                                      \n                val x = new StringBuffer(\"Hello\")                         \n                val r1 = x.append(\", World\").toString                           \n                println(s\"StrBuffer appended direct value - r1 : $r1\")          \n                val r2 = x.append(\", World\").toString                           \n                println(s\"StrBuffer appended direct value - r2 : $r2\")          \n        }                                                                       \n}                                                                               \n<\/pre>\n<p>The above scala program has two different methods &#8211; <code>strBufferAppend()<\/code> and <code>refTransparencyStrBuffer()<\/code>, in addition to the typical <code>main()<\/code> method. The <code>strBufferAppend()<\/code> method defines one value <code>Hello<\/code> to a variable <code>x<\/code> as an initial value while instantiating a <code>StringBuffer<\/code> instance. It then appends another string <code>\", World\"<\/code> with the existing value of <code>x<\/code> and assigns it to a new varaible <code>y<\/code>. It then invokes the <code>toString()<\/code> on the variable <code>y<\/code>, which will return the value of &#8216;y&#8217; that is assigned to the variable <code>r1<\/code> which gets printed on the next line. Similarly it invokes the <code>toString()<\/code> on &#8216;y&#8217; and assigns to another variable <code>r2<\/code> which gets printed in the subsequent line.[ulp id=&#8217;r5HxHBP7fqxvOHkw&#8217;]<\/p>\n<p>The next method <code>refTransparencyStrBuffer<\/code> does the same thing but with a difference like the previous program. Rather than assigning the input String to a variable <code>y<\/code> and then using the variable&#8217;s value for subsequent <code>toString()<\/code> operations for assigning to <code>r1<\/code> and <code>r2<\/code>, this method directly places the value of &#8216;y&#8217; which is <code>x.append(\", World\")<\/code> in place of &#8216;y&#8217; in both r1 and r2&#8217;s assignment.<\/p>\n<p>Let us see the output of the above program.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\scalaPgms\\&gt; scalac ReferentialTransparencyBroken.scala\n\nC:\\Users\\scalaPgms\\&gt; scala ReferentialTransparencyBroken\n\n ------------ StringBuffer Append ---------------\nStrBuffer appended variable value - r1 : Hello, World\nStrBuffer appended variable value - r2 : Hello, World\n\n ======== Referential Transparency (broken) =======\nStrBuffer appended direct value - r1 : Hello, World\nStrBuffer appended direct value - r2 : Hello, World, World\n\n<\/pre>\n<p>As you see, the <code>strBufferAppend<\/code> method did not have anything different as we were using the value of a variable. However the output of <code>refTransparencyStrBuffer<\/code> was different because we had replaced the value of &#8216;y&#8217; &#8211; which is <code>x.append(\", World\")<\/code> in place of &#8216;y&#8217; during the assignment of r1 and r2.<\/p>\n<p>If you observe closely, at first when the value <code>x.append(\", World\")<\/code> was assigned to r1, the value of r1 was <code>\"Hello, World\"<\/code> properly. However the value of <code>x<\/code> was indirectly changed to &#8220;Hello, World&#8221; as opposed to the original &#8220;Hello&#8221; due to the <code>append()<\/code> method. When the same replacement happens again for &#8216;r2&#8217;, the value <code>x.append(\", World\")<\/code> will be evaluated to <code>\"Hello, World\".append(\", World\")<\/code> and hence the result was produced as <code>\"Hello, World, World\"<\/code>. Hence, we cannot say that the <code>append<\/code> method is referentially transparent.<\/p>\n<h3><a name=\"fp-concepts-pure-impure-fns\"><\/a>4.4. Pure and Impure functions<\/h3>\n<p>Having understood about the immutability, we can get this terminology in an easy manner.<\/p>\n<blockquote>\n<p>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.<\/p>\n<\/blockquote>\n<p>It is more of a mathematical function <code>sin(x)<\/code> where this function will always give the same output for the same <code>x<\/code> value, no matter how many times we invoke. This forms the very basics of Functional Programming. The <code>sin(x)<\/code> is a pure function due to the nature of its implementation.<\/p>\n<p>We can say that from the previous examples, <code>plusOne()<\/code> method in <code>SideEffect.scala<\/code> is a pure function. The same way, the <code>append()<\/code> method of <code>StringBuilder<\/code> is an impure function as demonstrated in the <code>ReferentialTransparencyBroken.scala<\/code> class.<\/p>\n<h3><a name=\"fp-concepts-higer-order-fns\"><\/a>4.5. Higher Order Functions<\/h3>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>Let us see an example program to understand the same.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>HigherOrderFunctions.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">object HigherOrderFunctions {\n        def main(args:Array[String]):Unit = {\n                val add = (x:Int, y:Int) =&gt; { x + y }\n                operation(add)\n\n                val subtract = (x:Int, y:Int) =&gt; { x - y }\n                operation(subtract)\n\n                val multiply = (x:Int, y:Int) =&gt; { x * y }\n                operation(multiply)\n        }\n\n        def operation(f:(Int,Int) =&gt; Int) {\n           println(f(5,5))\n        }\n}\n<\/pre>\n<p>The above Scala program has a function named <code>operation<\/code> that takes a function as an input parameter\/argument which is <code>f:(Int,Int) =&gt; Int<\/code> &#8211; indicating that the function <code>f<\/code> will accept two integer parameters and will return an integer value. The <code>operation<\/code> method will indeed invoke the passed function <code>f<\/code> with the values <code>5, 5<\/code> for the <code>f<\/code> to work.<\/p>\n<p>We had defined 3 different methods <code>add<\/code>, <code>subtract<\/code> and <code>multiply<\/code> 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 &#8216;x&#8217; and &#8216;y&#8217;.<\/p>\n<p>The <code>main()<\/code> method invokes the function <code>operation<\/code> three times subsequently by passing each of the mathematical functions one at a time.<\/p>\n<p>The output of the program is given as below.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\scalaPgms\\&gt; scala HigherOrderFunctions\n10\n0\n25\n<\/pre>\n<p>As you see, the main() method invoked the 3 different mathematical functions &#8211; add, subtract, multiply. The <code>operation<\/code> method invoked the corresponding function which is received as an input with the input values &#8216;5&#8217;, and &#8216;5&#8217; for all the functions. Hence we see the output as <b>10<\/b> for &#8216;add&#8217;, <b>0<\/b> for &#8216;subtract&#8217; and <b>25<\/b> for &#8216;multiply&#8217;.<\/p>\n<p>We can call the method <code>operation<\/code> as a <b>Higher Order Function (HOF)<\/b> since it works with another function passed as an argument. Similarly a function can also return a function as a result.<\/p>\n<h2><a name=\"example\"><\/a>5. Example Program &#8211; SumOfSquaresOfOdd<\/h2>\n<p>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.<\/p>\n<h3><a name=\"example-imper\"><\/a>5.1 SumOfSquaresofOdd &#8211; Imperative Way (Java)<\/h3>\n<p>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).<\/p>\n<p><span style=\"text-decoration: underline;\"><em>SumOfSquaresOfOdd.java<\/em><\/span><\/p>\n<pre class=\"brush:java;\">import java.util.*;\n\npublic class SumOfSquaresOfOdd\n{\n    public static void main(String... args)\n    {\n        List intList = new ArrayList();\n\n        for(int i = 1; i &lt;= 5; i++) {\n                intList.add(i);\n        }\n\n        System.out.println(\"intList - Initial : \" + intList);\n\n        List oddNoList = new ArrayList();\n\n        for(int i = 0; i &lt; intList.size(); i++) {\n                if(intList.get(i)%2==1) {\n                        oddNoList.add(intList.get(i));\n                }\n        }\n\n        System.out.println(\"oddNoList : \" + oddNoList);\n\n        List squareList  = new  ArrayList();\n\n        for(int i=0; i &lt; oddNoList.size(); i++) {\n                squareList.add(oddNoList.get(i) * oddNoList.get(i));\n        }\n\n        System.out.println(\"squareList : \" + squareList);\n\n        int sum = 0;\n        for(Integer i : squareList) {\n                sum += i;\n        }\n\n        System.out.println(\"Sum : \" + sum);\n    }\n}\n<\/pre>\n<p>The above program has a <code>main()<\/code> method that has the detailed steps indicating <b>How<\/b> to do the problem solving step by step, wherein defining an <code>intList<\/code> having a list of Integers, preparing a <code>oddNoList<\/code> by looping through the input list <code>intList<\/code> and then preparing another list called <code>squareList<\/code> by iterating the <code>oddNoList<\/code> for finding the square value of each number, and finally iterating the <code>squareList<\/code> to iterate each element to calculate the sum of each element in the list.<\/p>\n<p>For each iteration, we had used a temporary varaible <code>i<\/code>, 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.<\/p>\n<p>The output of the above program is given below.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\javaPgms\\&gt; javac SumOfSquaresOfOdd.java\n\nC:\\Users\\javaPgms\\&gt; java SumOfSquaresOfOdd\nintList - Initial : [1, 2, 3, 4, 5]\noddNoList : [1, 3, 5]\nsquareList : [1, 9, 25]\nSum : 35\n<\/pre>\n<p>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.<\/p>\n<h3><a name=\"example-fp\"><\/a>5.2 SumOfSquaresOfOdd &#8211; Functional Way (Scala)<\/h3>\n<p>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 &#8216;ceremonies&#8217;.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>SumOfSquaresOfOdd.scala<\/em><\/span><\/p>\n<pre class=\"brush:java;\">import scala.collection.immutable.List\n\nobject SumOfSquaresOfOdd\n{\n        def main(args:Array[String]):Unit =\n        {\n                var intList = List(1,2,3,4,5)\n                def sum = intList.filter(x =&gt; x % 2 ==1).map(x =&gt; x * x).reduce((x,y) =&gt; x+y)\n                println(sum)\n        }\n}\n<\/pre>\n<p>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 <code>filter<\/code> method to pick up the odd numbers, <code>map<\/code> method to iterate each element of the list\/collection by applying a square of each value, <code>reduce<\/code> method to walk through each element in a collection to sum them up all.<\/p>\n<p>At the outset, we never say <b>How<\/b> to do the operation rather we just say <b>what<\/b> to do in a functional or declarative way, leaving aside the implementation to Scala itself.<\/p>\n<p>The output of the above program is given below.<\/p>\n<pre class=\"brush:java;\">C:\\Users\\scalaPgms\\&gt; scalac SumOfSquaresOfOdd.scala\n\nC:\\Users\\scalaPgms\\&gt; scala SumOfSquaresOfOdd\n35\n<\/pre>\n<p>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.<\/p>\n<h2><a name=\"adv-fp\"><\/a>6. Advantages of Functional Programming<\/h2>\n<p>The functional programming due to its nature of favoring and honoring the core concepts such as Higher Order Functions, pure functions, immutability, referential transparency &#8211; offers several advantages &#8211; of which few of them are listed below.<\/p>\n<p><b>Clean and Conside code<\/b> &#8211; due to the several built in API methods offerred by Scala, the code becomes very clean and concise.<\/p>\n<p><b>Modurality and better reusability<\/b> &#8211; 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.<\/p>\n<p><b>Reduced Coupling<\/b> &#8211; 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.<\/p>\n<p><b>Better and Efficient Unit Testing <\/b> &#8211; as there is no immutability and functions are mostly pure, it is easy to do an efficien Unit Testing, since we don&#8217;t need to really bother about any side effects like global state change.<\/p>\n<p><b>Better Concurrent Programming<\/b> &#8211; 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.<\/p>\n<h2><a name=\"conclusion\"><\/a>7. Conclusion<\/h2>\n<p>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.<\/p>\n<h2><a name=\"ref\"><\/a>8. References<\/h2>\n<p>You may please refer the following URLs for further reading.<\/p>\n<ol>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/scala-tutorial-beginners\">Scala Tutorial for Beginners &#8211; JCG<\/a><\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Functional_programming\">Functional Programming &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Referential_transparency\">Referential Transparency &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Side_effect_%28computer_science%29\">Side Effect &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Pure_function\">Pure Function &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/pragprog.com\/magazines\/2013-01\/functional-programming-basics\">Functional Programming Basics<\/a><\/li>\n<li><a href=\"http:\/\/www.cse.chalmers.se\/~rjmh\/Papers\/whyfp.html\">Why Functional Programming<\/a><\/li>\n<li><a href=\"http:\/\/c2.com\/cgi\/wiki?FunctionalProgramming\">Functional Programming &#8211; C2 wiki<\/a><\/li>\n<li><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/bb669144.aspx\">Functional Programming vs. Imperative Programming<\/a><\/li>\n<li><a href=\"http:\/\/blog.jenkster.com\/2015\/12\/what-is-functional-programming.html\">What is Functional Programming<\/a><\/li>\n<li><a href=\"http:\/\/www.slideshare.net\/pramode_ce\/introduction-to-functional-programming-with-scala\">Intro to FP with Scala<\/a><\/li>\n<li><a href=\"http:\/\/jim-mcbeath.blogspot.in\/2009\/05\/scala-functions-vs-methods.html\">Scala &#8211; Functions Vs Methods<\/a><\/li>\n<\/ol>\n<h2><a name=\"download\"><\/a>9. Download the Source Code<\/h2>\n<p>All the examples in this article are tested in the Command Prompt \/ Shell against Scala Version 2.11.7.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <strong><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/05\/functionalProgrammingInScala.zip\">Functional Programming in Scala<\/a><\/strong>.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>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 &#8211; a style of building the structure and elements of computer programs\u2014that treats computation as the evaluation of &hellip;<\/p>\n","protected":false},"author":87,"featured_media":36666,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1462],"tags":[1469,1245],"class_list":["post-36937","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scala","tag-functional-programming","tag-scala"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Functional Programming in Scala - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Functional Programming in Scala - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2016-05-09T08:00:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-29T12:05:56+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Raghavan Muthu\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/itsraghz\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Raghavan Muthu\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"26 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\"},\"author\":{\"name\":\"Raghavan Muthu\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\"},\"headline\":\"Functional Programming in Scala\",\"datePublished\":\"2016-05-09T08:00:24+00:00\",\"dateModified\":\"2019-03-29T12:05:56+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\"},\"wordCount\":4300,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg\",\"keywords\":[\"Functional Programming\",\"Scala\"],\"articleSection\":[\"Scala\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\",\"name\":\"Functional Programming in Scala - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg\",\"datePublished\":\"2016-05-09T08:00:24+00:00\",\"dateModified\":\"2019-03-29T12:05:56+00:00\",\"description\":\"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JVM Languages\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Scala\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/scala\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Functional Programming in Scala\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\",\"name\":\"Raghavan Muthu\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"caption\":\"Raghavan Muthu\"},\"description\":\"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).\",\"sameAs\":[\"https:\/\/www.raghsonline.com\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/itsraghz\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Functional Programming in Scala - Java Code Geeks","description":"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/","og_locale":"en_US","og_type":"article","og_title":"Functional Programming in Scala - Java Code Geeks","og_description":"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of","og_url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2016-05-09T08:00:24+00:00","article_modified_time":"2019-03-29T12:05:56+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg","type":"image\/jpeg"}],"author":"Raghavan Muthu","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/itsraghz","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Raghavan Muthu","Est. reading time":"26 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/"},"author":{"name":"Raghavan Muthu","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315"},"headline":"Functional Programming in Scala","datePublished":"2016-05-09T08:00:24+00:00","dateModified":"2019-03-29T12:05:56+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/"},"wordCount":4300,"commentCount":2,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg","keywords":["Functional Programming","Scala"],"articleSection":["Scala"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/","url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/","name":"Functional Programming in Scala - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg","datePublished":"2016-05-09T08:00:24+00:00","dateModified":"2019-03-29T12:05:56+00:00","description":"In this Tutorial article, we will see how to work with Functional Programming in Scala Programming Language. According to Wikipedia, the definition of","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/04\/scala-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/scala\/functional-programming-scala\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"JVM Languages","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/"},{"@type":"ListItem","position":3,"name":"Scala","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/scala\/"},{"@type":"ListItem","position":4,"name":"Functional Programming in Scala"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315","name":"Raghavan Muthu","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","caption":"Raghavan Muthu"},"description":"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).","sameAs":["https:\/\/www.raghsonline.com\/","https:\/\/x.com\/https:\/\/twitter.com\/itsraghz"],"url":"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/36937","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=36937"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/36937\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/36666"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=36937"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=36937"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=36937"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}