Kotlin Variables

val vs var

Kotlin uses two keywords to declare variables:

  • val — read-only (like a final variable)
  • var — mutable (can be reassigned)
val name: String = "Alice"  // immutable
var age: Int = 25          // mutable

Type Inference

Kotlin can automatically detect the type, so you can omit the explicit type:

val language = "Kotlin"
var version = 1.9

The type will still be statically checked by the compiler.

Reassigning Variables

You can reassign var variables, but not val ones:

var counter = 5
counter += 1  // ✅ OK

val year = 2024
year = 2025   // ❌ Error: val cannot be reassigned

Best Practices

  • Prefer val by default for safety
  • Use var only when mutation is needed
  • Use descriptive names (camelCase)

Constants

To declare compile-time constants, use const val inside top-level or object declarations:

const val PI = 3.14159

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic