Home » Blog » Variables

Variables

Kotlin has powerful type inference. While you can explicitly declare the type of a variable, you’ll usually let the compiler do the work by inferring it. Kotlin does not enforce immutability, though it is recommended. In essence use val over var.

var a: String = "initial"  
println(a)
val b: Int = 1             
val c = 3
  • Declares a mutable variable and initializing it.
  • Declares an immutable variable and initializing it.
  • Declares an immutable variable and initializing it without specifying the type. The compiler infers the type Int.
var e: Int  
println(e)
  • Declares a variable without initialization.
  • An attempt to use the variable causes a compiler error: Variable ‘e’ must be initialized.
You’re free to choose when you initialize a variable, however, it must be initialized before the first read.
val d: Int  

if (someCondition()) {
    d = 1   
} else {
    d = 2   
}

println(d)
  • Declares a variable without initialization.
  • Initializes the variable with different values depending on some condition.
  • Reading the variable is possible because it’s already been initialized.
Tags:

Leave a Reply

Your email address will not be published.