- Kotlin Programming By Example
- Iyanu Adelekan
- 283字
- 2021-08-27 20:00:07
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.
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- INSTANT OpenCV Starter
- Mastering OpenCV Android Application Programming
- 算法訓練營:入門篇(全彩版)
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- 數據結構簡明教程(第2版)微課版
- C程序設計實踐教程
- RabbitMQ Cookbook
- AIRIOT物聯網平臺開發框架應用與實戰
- Java SE實踐教程
- Java編程從入門到精通
- Java程序設計教程
- 基于GPU加速的計算機視覺編程:使用OpenCV和CUDA實時處理復雜圖像數據
- SSH框架企業級應用實戰
- WCF技術剖析(卷1)