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

Variables

A variable is an identifier for a memory location that holds a value. A simpler way to describe a variable is an identifier that holds a value. Consider the following program:

fun main(args: Array<String>) {
var x: Int = 1
}

The preceding x is a variable and the value it holds is 1. More specifically, x is an integer variable. The x is referred to as an integer variable because x has been defined to have the Int data type. As such, the x variable can only hold an integer value. To be more accurate, we say that x is an instance of the Int class. At this point, you must be wondering what the words instance and class mean in this context. All will be revealed in due time. For now, let's focus on the topic of variables.

When defining a variable in Kotlin, we make use of the var keyword. This keyword specifies that the variable is mutable in nature. Thus, it can be changed. The data type of the declared variable comes after a semicolon that follows the variable's identifier. It is important to note that the data type of a variable need not be explicitly defined. This is because Kotlin supports type inference—the ability to infer types of objects upon definition. We might as well have written the definition of our x variable as:

var x = 1

The outcome of the definition would be the same. A semicolon can be added to the end of the line of our variable definition but, similar to languages like JavaScript, it is not required:

var x = 1 // I am a variable identified by x and I hold a value of 1
var y = 2 // I am a variable identified by y and I hold a value of 2
var z: Int = x + y // I am a variable identified by z and I hold a value of 3

If we don't want the values of our variables to change over the course of the execution of our program, we can do so by making them immutable. Immutable variables are defined with the val keyword, as follows:

val x = 200
主站蜘蛛池模板: 松潘县| 五家渠市| 晋城| 塘沽区| 廉江市| 安宁市| 库尔勒市| 宝清县| 连州市| 桐梓县| 启东市| 微山县| 平远县| 乌恰县| 克拉玛依市| 商城县| 松滋市| 济阳县| 施甸县| 商南县| 浪卡子县| 靖宇县| 商河县| 武邑县| 自贡市| 临邑县| 商洛市| 鄂州市| 华亭县| 芜湖市| 璧山县| 武城县| 探索| 东阿县| 博白县| 常山县| 康定县| 油尖旺区| 安庆市| 江山市| 韶关市|