Closures

In the examples you’ve seen so far in this chapter, the variables and values used in the function values or code blocks were bound. You clearly knew what they were bound to, local variables or parameters. In addition, you can create code blocks with variables that are not bound. You’ll have to bind them before you can invoke the function; however, they could bind to, or close over, variables outside of their local scope and parameter list. That’s why they’re called closures.

Let’s look at a variation of the totalResultOverRange method you saw earlier in this chapter. The method loopThrough in this example iterates over the elements from 1 to a given number:

FunctionValuesAndClosures/Closure.scala
 
def​ loopThrough(number: ​Int​)(closure: ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.