- Scala - Files I/O
- Scala - Extractors
- Scala - Exception Handling
- Scala - Regular Expressions
- Scala - Pattern Matching
- Scala - Traits
- Scala - Collections
- Scala - Arrays
- Scala - Strings
- Scala - Closures
- Scala - Functions
- Scala - Loop Statements
- Scala - IF ELSE
- Scala - Operators
- Scala - Access Modifiers
- Scala - Classes & Objects
- Scala - Variables
- Scala - Data Types
- Scala - Basic Syntax
- Scala - Environment Setup
- Scala - Overview
- Scala - Home
Scala Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Scala - Closures
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 multipper = (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 multipper = (i:Int) => i * factor
There are two free variables in multipper: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multipper is called. However, factor is not a formal parameter, then what is this? Let us add one more pne of code.
var factor = 3 val multipper = (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( "multipper(1) value = " + multipper(1) ) println( "multipper(2) value = " + multipper(2) ) } var factor = 3 val multipper = (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
multipper(1) value = 3 multipper(2) value = 6Advertisements