Home » Scala language

Closures in Scala

Closures are a special type of functions that rely on values other than its arguments for returning values. In this article, we will learn closure, with example and program.
Submitted by Shivang Yadav, on June 23, 2019

Closures in Scala

Closures in Scala are a special type of functions. Closures use one or more values that are not declared in the function to give the final output. This means their return value is dependent on values that are declared outside the function ( i.e. declared neither in the arguments nor in function body).

So, where did the value come from?

The other value(s) that are used by the closure can be defined anywhere outside the function but in the scope of the function. This means a value defined in other function cannot be used in closure but any variable defined in the same class or a global value can be used.

Taking the following function:

    val increment = (i:Int) => i + 2

Here, the function is an anonymous function but that uses a value other than its arguments but it is not a closure because it's not a variable.

So to define it as a closure,

    val increment = (i:Int) => i + adder

This one a closure as it used a variable that needs to be initialized outside the function for calculating the return value. We can initialize this adder variable anywhere before the function in our code.

For example,

    var adder = 2; 
    // code block; 
    val increment = (i:Int) => i + adder

Example code:

object Demo {
    var adder = 2
    def main(args: Array[String]) {
        println( "This code will increment the value by using closure");
        println("increment(10) = " + increment(10));
    val increment = (i:Int) => i + adder


This code will increment the value by using closure
increment(10) = 12

Example explanation:

In the above code, we have defined adder variable that is the outer variable to the closure. Then in the main method, we call the closure function with argument 10. The increment closure takes the value and adder the value of adder (2) to the argument and returns the final value (12).

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.