- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 313字
- 2021-06-10 18:49:18
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.
- iOS面試一戰(zhàn)到底
- MySQL數(shù)據(jù)庫(kù)管理實(shí)戰(zhàn)
- C/C++常用算法手冊(cè)(第3版)
- Learn Programming in Python with Cody Jackson
- Python機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- Python Web數(shù)據(jù)分析可視化:基于Django框架的開發(fā)實(shí)戰(zhàn)
- Mastering Unity 2D Game Development(Second Edition)
- Hands-On GUI Programming with C++ and Qt5
- 區(qū)塊鏈項(xiàng)目開發(fā)指南
- Learning iOS Security
- Ext JS 4 Plugin and Extension Development
- Hacking Android
- Learning Grunt
- Mobile Forensics:Advanced Investigative Strategies
- SAP Web Dynpro for ABAP開發(fā)技術(shù)詳解:基礎(chǔ)應(yīng)用