Hello there! Our adventure takes us into the captivating realm of Scala programming — function scope. Think of Grandma's interspersed secret apple pie recipe in her diary. The recipe, akin to a function, guards a secret ingredient (a variable) that is confined within the recipe. Similarly, function scope refers to the specified section of the code where variables are defined and recognized. A variable declared inside a function, known as a local variable, exists only within that function.
Let's take a look at the following code snippet:
In this scenario, secretCode is only defined within the printSecret function. This variable won't be recognized within the outer run function.
There are two types of scopes:
- Local variable: This is akin to a green room for an actor, known only within the function where it is established.
- Global variable: This is equivalent to a celebrity recognized all over the world, declared outside all functions and visible to any function within the same program.
Here's an example showcasing both:
This example shows that localCode can only be used inside the printCodes function, whereas globalCode enjoys visibility throughout the program.
Variable shadowing in Scala occurs when a local variable in a more inner scope (like a function or a block) has the same name as a variable in an outer scope, effectively "hiding" the outer variable within the inner scope. This means that any reference to the variable name within the inner scope will refer to the inner variable, not the outer one. Shadowing allows for the reuse of variable names but requires careful attention to avoid confusion and potential errors in the code's logic.
To shadow an immutable variable, you need to use the val keyword again. If you don't, you'll encounter an error, as Scala will not allow reassignments without the declaration keyword.
When it comes to mutable variables, shadowing can also occur with the var keyword. However, just like with val, you must use the var keyword again to shadow a mutable variable.
