官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 阿勒泰市| 张家界市| 青铜峡市| 宁化县| 大关县| 阿合奇县| 涞水县| 武平县| 西乌珠穆沁旗| 丰城市| 瓮安县| 荔波县| 津南区| 黄大仙区| 蕲春县| 通辽市| 通渭县| 安岳县| 遵义县| 淳化县| 宁安市| 贡山| 西和县| 高邑县| 黔东| 新邵县| 盐池县| 昂仁县| 莒南县| 石柱| 商都县| 锡林浩特市| 灵武市| 万安县| 保定市| 云和县| 吉安市| 广平县| 天台县| 麦盖提县| 同江市|