Variable scope

The scope of a variable is the region of a program where the variable is of consequence. In other words, the scope of a variable is the region of a program in which the variable can be used. Kotlin variables have block scope. Therefore, the variables can be utilized in all regions that the block they were defined in covers:

fun main(args: Array<String>) {
// block A begins
var a = 10
var i = 1

while (i < 10) {
// block B begins
val b = a / i
print(b)
i++
}
print(b) // Error occurs: variable b is out of scope
}

In the preceding program, we can directly observe the effects of block scope by taking a look at the two blocks. The definition of a function opened a new block. We have labeled to this block as B in our example. Within A, the a and i variables were declared. As such, the scope of the a and i variables exists within A.

A while loop was created within A, and as such, a new B block was opened. Loop declarations mark the beginning of new blocks. Within B, a b value is declared. The b value exists in the B scope and can't be used outside its scope. As such, when we attempt to print the value held by b outside the B block, an error will occur.

One thing worth noting is that the a and i variables can still be utilized within the B block. This is because B exists within the scope of A.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.97.75