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