Basic Kotlin
Basic Kotlin
Let’s first learn some basic commands to get familiar with Katlin which is an open-source statically typed programming language that runs on Java Virtual Machine (JVM).
Kotlin Variable
Variables are used to store data to be manipulated and referenced in the program. It is fundamentally a unit of storing data and labeling it waits for an expository alias so that the program is simple to read and easy to understand. In other words, we can say that variables are the containers to collect information.
In Kotlin, all the variables should be declared. However, if any variable is not declared, then it pops out to be a syntax error. Also, the declaration of the variable determines the type of data we are allowing to store in the variable. In Kotlin, variables can be defined using val and var keywords.
Let see how var and val keywords are different from each other.
Var :
Var is like a generic variable used in any programming language that can be utilized multiple times in a single program. Moreover, you can change its value anytime in a program. Therefore, it is known as the mutable variable.
Here is an example of mutable variable in Kotlin:
var num1 = 10Var num2 = 20Num1 = 20print(num1 + num2) // output : 40
Here the value of num1 that is 20, is overwritten by the previous value of num1 that is 10. Therefore the output of num1 + num2 is 40 instead of 30.
Val:
Val is like a constant variable, and you cannot change its value later in the program, which neither can be assigned multiple times in a single program and can be used only once in a particular program. Ergo, it is known as an immutable variable.
Here is an Kotlin program example of immutable variables in Kotlin:
Val num1 = 10Var num2 = 20
Here, the value of num1 that is 10 cannot be overwritten by the new value of num1 that is 20, as it is of val type that is constant. Therefore, the output is 30 instead of 40.
Note: In Kotlin, immutable variables are preferred over mutable variables.