Scala – Closure

  • date 24th April, 2021 |
  • by Prwatech |
  • 0 Comments

A Guide to Scala’s Closures

 

Closure is a function in scala, it’s return value depends on one or more variable which is declared outside the function.

In Scala, procedures and functions are closely related concepts but have distinct characteristics based on their definitions and usage within the language.

A function in Scala is a named block of code that takes zero or more input parameters and produces a result when invoked. Functions are defined using the def keyword and explicitly specify a return type. They are first-class citizens in Scala, meaning they can be assigned to variables, passed as arguments, and returned from other functions. Functions in Scala always return a value, even if it’s Unit (similar to void in other languages).

On the other hand, a procedure in Scala is a special kind of function that does not return a value explicitly. Procedures are defined using the def keyword without specifying a return type (or specifying Unit explicitly). Procedures are primarily used for their side effects, such as printing to the console or modifying mutable state, rather than computing and returning values.

The distinction between functions and procedures highlights Scala’s functional programming capabilities and emphasizes the importance of clarity in side-effecting versus pure computations. While functions focus on producing results based on input parameters, procedures emphasize performing actions without necessarily returning a value. Understanding these differences is crucial for writing expressive and idiomatic Scala code.

use case 1:

object closure1 {

  def main(args: Array[String]) {

      println( “multiplier(1) value = ” +  multiplier(4) )

      println( “multiplier(2) value = ” +  multiplier(5) )

   }

   var factor = 5

   val multiplier = (i:Int) => i * factor

}

output

use case 2:

object closure2 {

    // Main method

    def main(args: Array[String])

    {

        println( “Final_Sum(1) value = ” + sum(1))

        2println( “Final_Sum(2) value = ” + sum(2))

        println( “Final_Sum(3) value = ” + sum(3))

    }

    var a = 4

    // define closure function

    val sum = (b:Int) => b + a

}

output

Here, In above program function sum is a closure function. var a = 4 is impure closure. the value of a is same and values of b is different.

use case 3:

object closure3 {

    // Main method

    def main(args: Array[String])

    {

        var employee = 30

        // define closure function

        val closure3 = (name: String) => println(s”Company name is $name”+

                       s” and total no. of employees are $employee”)

        closure3(“prwatech”)

    }

}

output

Here, In above example closure3 is a closure. var employee is mutable variable which can be change.

 

0
0

Quick Support

image image