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

Declaring variables

To declare a variable in Kotlin, we use either the val or var keywords.

Let's take a look at the following example:

val number = 10
println(number)

The preceding code prints the value that is assigned to a variable number, as can be seen in the following screenshot:

However, if we try to change the value assigned to the number, we will get a compilation error. Take a look at the following code:

val number = 10
println(number)
number = 11
println(number)

The output is as follows:

This is because val is immutable in Kotlin. This means that once a value is assigned, it cannot be modified. The keyword var, however, can be used to create a mutable variable.

Now consider the code for 3_valnVar.kts:

val number = 10
println(number)

var anotherNumber = 15
println(anotherNumber)

anotherNumber = 20
println(anotherNumber)

The output for the preceding code is as follows:

Let's examine what happens if we assign a string value to the preceding code:

val number = 10
println(number)

var anotherNumber = 15
println(anotherNumber)

anotherNumber = "20"
println(anotherNumber)

Compile this and see what happens:

In this case, the compiler throws an error saying that the type is mismatched. This is because the anotherNumber variable was inferred to be of type int and, as a result, we cannot assign a different type.

The type is inferred from the context and type safety is also guaranteed.

Both var and  val are used to declare variables in Kotlin. val creates immutable variables, and var creates mutable variables. Variables declared using the val keyword cannot be changed once a value is assigned to them. This is similar to a final variable in Java. val is used to create constants. Variables declared using the  var keyword can be changed later in the program. This corresponds to a regular Java variable.
主站蜘蛛池模板: 汶上县| 固阳县| 靖西县| 屏南县| 宜兰县| 固原市| 托克逊县| 宜州市| 芦溪县| 灌云县| 漾濞| 高淳县| 铁力市| 格尔木市| 肃北| 永安市| 卢氏县| 芜湖县| 呼和浩特市| 遵化市| 来宾市| 曲松县| 福清市| 察雅县| 鲁山县| 阜新市| 汽车| 乐昌市| 长岭县| 额济纳旗| 红河县| 巴中市| 潮州市| 宕昌县| 昆明市| 曲靖市| 麻栗坡县| 扎兰屯市| 安西县| 淮阳县| 得荣县|