Hello there! Our adventure today takes us into the captivating realm of Kotlin 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.
Consider this example:
In this scenario, secretCode
is only defined within the printSecret
function. This variable won't be recognized within the outer main
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:
