Variables & Data Types

Kotlin has two ways to declare a variable — one that locks the reference, one that doesn't — and it infers types automatically from whatever value you give it.

val vs var

Kotlin has two ways to declare a variable, and the choice is meaningful: val creates a read-only reference (assign it once, never reassign it), and var creates a mutable one you can reassign later:

</> main.kt
fun main() {
    val name = "Priya"
    var score = 80

    score = 95
    println("$name scored $score")
}
Output
Priya scored 95

Trying to reassign name = "Sam" below that would fail to compile with Val cannot be reassigned. Idiomatic Kotlin defaults to val everywhere it can — reach for var only when a value genuinely needs to change.

Type inference and basic types

Kotlin infers a variable's type from its initial value, so you rarely write the type out — but you can, and sometimes should for clarity:

</> main.kt
fun main() {
    val count: Int = 42
    val price = 19.99          // inferred as Double
    val initial = 'K'           // inferred as Char
    val isActive = true         // inferred as Boolean
    val label: String = "beta"

    println("$count $price $initial $isActive $label")
}
Output
42 19.99 K true beta

The core types are Int, Long, Double, Float, Boolean, Char, and String — all capitalized, since in Kotlin even primitives are technically objects (the compiler optimizes most of that away at the bytecode level).

Note: val makes the reference immutable, not necessarily the object it points to. val list = mutableListOf(1, 2, 3) can't be reassigned to a different list, but you can still call list.add(4) on it — the variable is locked, the object it names might not be.