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

Get Scala Functional Programming Patterns 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.