O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required