Kotlin Variables
In Kotlin, every variable should be declared before it’s used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
var rollno = 55 var name = "Praveen" println(rollno) println(name)
Above we have the local variable rollno whose value is 55 and it’s type is Integer because the literal type is Int and another variable is name whose type is String. In Kotlin, variables are declared using two types –
- Immutable using val keyword
- Mutable using var keyword
Immutable Variables –
Immutable is also called read-only variables. Hence, we can not change the value of the variable declared using val keyword.
val myName = "Gaurav" myName = "Praveen" // compile time error // It gives error Kotlin Val cannot be reassigned
Note: Immutable variable is not a constant because it can be initialized with the value of a variable. It means the value of immutable variable doesn’t need to be known at compile-time, and if it is declared inside a construct that is called repeatedly, it can take on a different value on each function call.
var myBirthDate = "02/12/1993" val myNewBirthDate = myBirthDate println(myNewBirthDate)
Mutable Variables –
In Mutable variable we can change the value of the variable.
var myAge = 25 myAge = 26 // compiles successfully println("My new Age is ${myAge}")
Output:
My new Age is 26
Scope of a variable – A variable exists only inside the block of code( {………….} ) where it has been declared. You can not access the variable outside the loop. Same variable can be declared inside the nested loop – so if a function contains an argument x and we declare a new variable x inside the same loop, then x inside the loop is different than the argument. Naming Convention – Every variable should be named using lowerCamelCase.
val myBirthDate = "02/12/1994"