SyntaxStudy
Sign Up
Kotlin val, var and Type Inference
Kotlin Beginner 1 min read

val, var and Type Inference

Kotlin uses two keywords for variable declaration: val for read-only (immutable) references and var for mutable references. Preferring val is considered idiomatic Kotlin because it communicates intent clearly and makes code safer in concurrent environments. The compiler infers types from the right-hand side of an assignment, so explicit type annotations are optional in most situations. You can always add them for clarity or when the compiler cannot infer the type, such as when declaring a variable without an initialiser. Kotlin's primitive-looking types (Int, Double, Boolean, Char) are full objects on the JVM but are compiled to primitive bytecode wherever possible, giving you the convenience of an object-oriented API with the performance of primitives.
Example
fun main() {
    // Immutable reference — cannot be reassigned
    val pi = 3.14159
    val greeting: String = "Hello"

    // Mutable reference
    var counter = 0
    counter += 1
    counter++

    // Explicit types
    val bigNumber: Long = 9_000_000_000L
    val hex: Int        = 0xFF
    val binary: Int     = 0b1010_1010

    // Type conversion — no implicit widening
    val intVal: Int    = 42
    val longVal: Long  = intVal.toLong()
    val doubleVal: Double = intVal.toDouble()

    println("pi=$pi counter=$counter")
    println("long=$longVal double=$doubleVal")

    // Late-initialised var (non-null, initialised before first use)
    lateinit var name: String
    name = "Kotlin"
    println("Language: $name")

    // Compile-time constants
    // const val MAX = 100  // only allowed at top level or in object
}

const val APP_VERSION = "1.0.0"   // top-level const