top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Please explain closure in Scala?

+2 votes
293 views
Please explain closure in Scala?
posted Jul 22, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

A closure is a function, whose return value depends on the value of one or more variables declared outside this function.

The following piece of code with anonymous function.

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

Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function. Try the following code −

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

There are two free variables in multiplier: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multiplier is called. However, factor is not a formal parameter, then what is this? Let us add one more line of code.

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

Now factor has a reference to a variable outside the function but in the enclosing scope. The function references factor and reads its current value each time. If a function has no external references, then it is trivially closed over itself. No external context is required.

Try the following example program.

Example

object Demo {
   def main(args: Array[String]) {
      println( "multiplier(1) value = " +  multiplier(1) )
      println( "multiplier(2) value = " +  multiplier(2) )
   }
   var factor = 3
   val multiplier = (i:Int) => i * factor
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

multiplier(1) value = 3
multiplier(2) value = 6
answer Sep 7, 2016 by Joy Nelson
Similar Questions
0 votes

Explain the main difference between List and Stream in Scala Collection API? How do we prove that difference? When do we choose Stream?

+1 vote

What is Either in Scala? What are Left and Right in Scala? Explain Either/Left/Right Design Pattern in Scala?

...