×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Closures in Scala

By IncludeHelp Last updated : October 20, 2024

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).

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.

Syntax

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.

Syntax

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 of Closures

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
}

Output

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.