Kotlin Variables
Kotlin gives you two keywords, val and var, to declare variables with different mutability guarantees.
What Are Variables?
A variable is a named storage location that holds a value your program can read and, in some cases, update. In Kotlin, every variable must be declared using either the val or var keyword before it can be used, and the compiler infers or checks its type at compile time.
Declaring with val
Declaring read-only values with val
fun main() {
val name = "Aditi"
val age = 27
val pi = 3.14159
println("$name is $age years old")
println("Pi is approximately $pi")
}Declaring with var
Reassigning a var
fun main() {
var score = 0
println("Starting score: $score")
score = 10
score += 5
println("Updated score: $score")
}The difference between val and var is not about performance, it is about intent. A val reference can only be assigned once; attempting to assign it a second time is a compile-time error, not a runtime one. A var can be reassigned as many times as needed, as long as the new value matches the variable's declared type.
- Start every declaration with val, then switch to var only if the compiler complains about reassignment.
- Use var for loop counters, accumulators, and values that genuinely change over time.
- Variable names should be camelCase and describe what the value represents, e.g. totalPrice, not tp.
- Kotlin variables cannot be read before they are initialized, so always assign a value or a default before use.
Type inference vs explicit typing
fun main() {
val inferredInt = 42 // Kotlin infers Int
val inferredDouble = 4.2 // Kotlin infers Double
val explicitLong: Long = 42L // explicit type annotation
var explicitString: String = "hello"
explicitString = "world"
println("$inferredInt $inferredDouble $explicitLong $explicitString")
}Exercise: Kotlin Variables
What is the key difference between val and var?