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.
If we define a function as shown below:
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.
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.
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.
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.
- Scala | Either
- Set in Scala | Set-2
- Set in Scala | Set-1
- Scala Map
- Scala | REPL
- Scala Map max() method with example
- Scala Map min() method with example
- Scala | Polymorphism
- Scala | Arrays
- Scala | Trait App
- Scala | ArrayBuffer
- Scala | Tuple
- Enumeration in Scala
- Iterators in Scala
- Scala Map take() method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : aarthipa