O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

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

Roping in a scope

A variable lives in a scope. A scope defines an area, for example, the body of a function where variables exist. A lexical scope (also known as static scope) defines how variable names are resolved in nested functions. Inner functions contain the scope of enclosing (parent) functions.

Variables defined in the parent functions are available to the inner functions. Variables have the habit of coming in and going out of a scope.

For example, consider the following Java code snippet:

…
int v = 9;
…
for (int v = 0; v < 10; ++v) { // compilation error 
   // Do something 
}   

The compiler will flag an error, as there is already another variable v in the scope.

Why does the following, slightly weird, Java code compile though? Let's check:

 int ...

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