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. While Kotlin does not enforce immutability, it is recommended. In essence use val over var.

fun main(args: Array<String>) {
//sampleStart
    var a: String = "initial" // 1
    println(a)

    val b: Int = 1 //2

    val c = 3 //3
//sampleEnd
}
  1. Declare a mutable variable and initialise it
  2. Declare an immutable variable and initialise it
  3. Declare an immutable variable and initialise it. The compiler infers the type.
fun main(args: Array<String>) {
//sampleStart
var e: Int //1
println(e) //2
//sampleEnd
}
  1. Declare a mutable variable, but don’t initialise it.
  2. Produces compiler error: Variable ‘e’ must be initialized