The var keyword

The var keyword declares a mutable property or local variable. This means that the variable can be changed or updated as follows during the course of the entire program:

var age = 25

In the preceding code, var is a keyword, age is a variable name, and 25 is an assigned integer value. Let's see some other variable definitions to understand the declarations better:

  • var myChar = 'A': myChar is a single character variable
  • var name = "Bob": A name is a string type variable
  • var age = 10: age is an integer type variable
  • var height = 5.10: height is a double type variable

In Kotlin, a variable must have a value assigned. Without proper initialization, it does not allow variable declarations:

var age //In-Valid Declaration; compiler error
var age = 25
Valid Declaration

The value of the variable can be changed, but the variable type itself cannot be changed. If we try to re-assign an integer variable with double or string, the compiler will throw the mismatch error type:

var age = 10 // Data type integer - Valid declaration
age = 10.2 // Invalid assignment - not an integer compiler error
age = "hello" // Invalid assignment not an integer - compiler error

It is necessary that we declare different variables with the var keyword, as demonstrated here:

fun main(args: Array<String>) {
var student = "Bob" // String variable
var age = 25 // Integer variable
var height = 5.6 // Double variable
println("Name is $student age is $age and height is $height")
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.191