BeginnerLesson 2 of 16
Variables, Types & String Templates – Kotlin
val and var, type inference, number types, and text with values.
With val you declare an immutable variable (like final), with var a mutable one. The type is usually inferred from the value (type inference), but you can specify it explicitly.
val name = "Ada" // String, immutable
var alter = 36 // Int, mutable
alter += 1
val gross = 3_000_000_000L // Long (L suffix)
val groesse: Double = 1.68
val f = 1.5f // Float
val aktiv = true
val buchstabe = 'A' // Char
// name = "Bob" // Error: val cannot be reassigned
println("$name is $alter, next year ${alter + 1}")String templates: $name inserts a variable, ${...} an arbitrary expression. Kotlin never converts numbers automatically – you call toInt(), toLong(), toDouble() explicitly.
println(7 / 2) // 3 (integer division)
println(7 / 2.0) // 3.5
println(7 % 2) // 1
val i: Int = 5
val l: Long = i.toLong() // explicit, otherwise an error
println("42".toInt() + 1) // 43
println("x".toIntOrNull()) // null
println(Int.MAX_VALUE + 1) // -2147483648 (overflow!)
println("a" == "a") // true: == calls equalsWarningIn Kotlin,
== compares the content (equals), while === compares the reference. Unlike in Java, you do not need .equals for strings.TipWhen in doubt, always use
val. Immutable values make code easier to understand and thread-safe – use var only when the value really has to change.