The Wayback Machine - https://web.archive.org/web/20240801114306/https://www.geeksforgeeks.org/scala-closures/
Open In App

Scala | Closures

Last Updated : 05 Nov, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function. So the difference between a closure function and a normal function is the free variable. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function. A free variable is not bound to a function with a valid value. The function does not contain any values for the free variable.
Example:
If we define a function as shown below:




def example(a:double) = a*p / 100


Now on running the above code we’ll get an error starting not found p. So now we give a value to p outside the function.




// defined the value of p as 10
val p = 10
  
// define this closure.
def example(a:double) = a*p / 100


Now the above function is ready to run as the free variable has a value. Now if we run the functions as:

Calling the function: example(10000)
Input: p = 10
Output: double = 1000.0

Now what if the value of the free variable changes, how does the value of the closure function changes?
So basically what closure function does is, that it takes the most recent state of the free variable and changes the value of the closure function accordingly.

Input: p = 10
Output: double = 1000.0

Input: p = 20
Output: double = 2000.0

A closure function can further be classified into pure and impure functions, depending on the type of the free variable. If we give the free variable a type var then the variable tends to change the value any time throughout the entire code and thus may result in changing the value of the closure function. Thus this closure is a impure function. On the other-hand if we declare the free variable of the type val then the value of the variable remains constant and thus making the closure function a pure one.

Example:




// Addition of two numbers with 
// Scala closure
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        println( "Final_Sum(1) value = " + sum(1))
        println( "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:

Final_Sum(1) value = 5
Final_Sum(2) value = 6
Final_Sum(3) value = 7

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.
Example:




// Scala closure program to print a string
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
      
        var employee = 50
      
        // define closure function
        val gfg = (name: String) => println(s"Company name is $name"+
                       s" and total no. of employees are $employee")
          
        gfg("geeksforgeeks")
    }
}


Output:

Company name is geeksforgeeks and total no. of employees are 50.

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



Previous Article
Next Article

Similar Reads

Scala short <(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short <(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
Article Tags :
three90RightbarBannerImg