A closure in Scala is a function and the concept of closure is quite clear. However I have decided to discuss closure under its own lesson since it is a concept unique to Scala programming language.
So a closure is a function that uses a variable declare outside the function. Let’s take an example of the function below.
def makeUp(score: Double) = score + bonus
In the example, we see a function called makeUp that takes a parameter, score. However, you also see that this function uses another variable called bonus. So where is the bonus coming from? It is a free variable. What??
Free Variable
So what is heck is a “free variable”? It is not a parameter to the makeUp() function. Besides, it’s not also a local variable to the function. It is defined elsewhere outside the function such that the makeUp() function is free to use it. So we say the variable bonus is free variable to the makeUp() function.
Of course, if you try to compile the code above, it throws an error. So you must have the variable defined as shown below for the code to compile.
// Program to demostrate Closure object HigherOrderFunctions { val bonus: Int = 20 def makeUp(score: Double) = score + bonus def main(args: Array[String]): Unit ={ val finalScore: Double = makeUp(67.5); println("Final Score: " + finalScore) } }
This works as expected and produces the following output
Final Score: 87.5
Topics on Functions in Scala
- Function Declaration and Definition
- Calling a Function
- Nested Functions
- Function Call by Name
- Functions With Variable Parameters
- Functions With Default Arguments
- Functions With Named Arguments
- Recursive Functions
- Anonymous Functions
- Partially Applied Functions
- Higher-Order Functions (HOD)
- Currying Functions