AnyCompiler

Variables and Types

Kotlin has two ways to declare a variable: val creates a read-only binding — it can be assigned once and never reassigned — while var creates a mutable one. Unlike Java, where final is optional and easy to forget, Kotlin nudges you toward val by making it the shorter, more idiomatic keyword; you reach for var only when you genuinely need to reassign.

fun main() {
    val name = "Kotlin"
    var count = 0
    count = count + 1
    println(name + " " + count)
}
Output
Kotlin 1

Both val and var infer their type from the initializer — name is inferred as String, count as Int. You can also write the type explicitly when it helps readability.

fun main() {
    val age: Int = 30
    val price: Double = 19.99
    val isStudent: Boolean = false
    val grade: Char = 'A'
    println("$age $price $isStudent $grade")
}
Output
30 19.99 false A

Note that Boolean prints as the lowercase word false, not False — a small detail, but a genuine difference from C#, which capitalizes it.

Next: operators and control flow — if as a real expression, for, while, and when.

Practice exercise

Declare a val temperature set to 72.5 and a val isSunny set to true. Print them together separated by a space.