Variables in Kotlin

To Declare a variable in Kotlin, we can start with val or var keyword then a variable name, optional data type, equality sign, and…

Variables in Kotlin

To Declare a variable in Kotlin, we can start with val or var keyword then a variable name, optional data type, equality sign, and variable value.

  • The keyword var (for variable) is used to declare the variables whose value might change over time. You can always reassign a value after initialization.
  • The keyword val (for value) is used to declare the variables whose value won’t change over time. After initialization, a new value cannot be reassigned.
fun main() { 
    val name = "Virat Kumar" 
    var age = 10 
    println(name) // Virat Kumar 
    println(age) //10 
    name = "virat"  // this will throw error because name is constant or read only variable 
    age = 12 
    println(age) // 12 
}

In the above example, the name is a constant whose value can’t be reassigned, whereas age is a variable whose value can be reassigned.

We can name variables using characters, underscores, and numbers but it can’t start with a number. For naming, we use the camelCase convention. In this convention, we don’t use spaces to separate words. we start with a lowercase word and for each word afterward, we start with an uppercase letter for the first letter.

Kotlin is a statically typed language. Even though we didn’t specify the type of variables declared above (name and age), Kotlin is smart enough to know the type from the value and Kotlin will use that type for that variable. This is called type inference. In the above example, the name is of type String and the age is of type Int.

We can also specify the type of variables if we want to

fun main() { 
    val name :String = "Virat Kumar" 
    var age :Int = 10 
    println(name) // Virat Kumar 
    println(age) //10 
}

The definition and Initialization of variables can be separated into two different lines. See below

fun main() { 
    val name :String  
    name = "Virat Kumar" 
    println(name) 
}

However, It is discouraged to use the definition and initialization of variables this way. If you forget to initialize the variable, the program will throw an error immediately.

We can assume that a variable should normally be initialized by using an equality sign after its declaration (val a = 10). But on the right side, It can be any expression. An expression is a piece of code that returns a value.

That’s it for this article and if you are interested in personal training for Kotlin, KMP, or Android development? Contact me at virat@codeancy.com to learn more!.