Kotlin variable declaration
In Kotlin there are two types of Variables.
- Mutable
- Immutable
Immutable variables are also known as Assign-once (read-only) variables. Assigned values to those variables can not be changed after the initialization is done. Values assigned to Mutable variables can be changed after the initialization at any time. That is the major contrast between Mutable and Immutable variables.
Assigned-once (Read only) variables
Immutable variables are declared by using the key word val in Kotlin.
val i = 26
val j: Int = 30
val k:Int // Can be joined with assignment
k = 97
val firstName: String = "Jhon"
firstName = "Michel" // Error: Val can not be reassigned
val secondName = "Dee"
Mutable variables
Mutable variable are declared by using the key word var.
var s = 90
var t:Int = 94
var lastName:String = "Stark"
lastName = "Lanister" // permitted to change the value
Type Inference in Kotlin
As we discussed in the previous article, Kotlin is a Statically Typed Programming language having said that it supports Type Inference also known as Deduction. In Java we have to explicitly mention the type of the variable. But in Kotlin it is not a must to mention the Type of any variable. In Kotlin, Compiler is able to identify the type of the variable for us during the compile time. Type Inference helps to reduce the Boilerplate code.
var arr = arrayOf(1, 1.4, "Tom")
var s = 90
val i = 26
Conclusion
In this article we discussed how to declare variables and what is type inference in Kotlin programming language. In future tutorials, We will be discussing more advance concepts as Arrays, Ranges, Conditionals, Collections etc.