Kotlin Variables — val, var, and Type Inference Explained
Kotlin has two ways to declare variables: val for read-only values and var for mutable ones. This tutorial explains both with practical examples.
What You Will Learn
- How to declare variables with val and var
- The difference between val and var
- How type inference works in Kotlin
- When to use explicit types
- Common variable mistakes to avoid
Declaring Variables in Kotlin
Syntax
val variableName = value
var variableName = value
val variableName: Type = valueBasic Variable Declaration
fun main() {
val language = "Kotlin"
var year = 2026
println(language)
println(year)
year = 2027
println(year)
}language is a val — it cannot be reassigned after declaration. year is a var — it can be updated, and we change it from 2026 to 2027.
Type Inference
Inferred vs Explicit Types
fun main() {
val name = "Kotlin" // inferred as String
val age: Int = 25 // explicit Int
val price = 9.99 // inferred as Double
val isActive = true // inferred as Boolean
println(name)
println(age)
println(price)
println(isActive)
}Kotlin infers the type from the right-hand side value. You can still write the type explicitly if it makes the code clearer — both styles are valid.
Declaring Without Immediate Assignment
Declare First, Assign Later
fun main() {
val result: Int
result = 10 + 5
println(result)
}result is declared as Int but assigned later. Kotlin ensures you cannot read result before it is assigned — this prevents uninitialized variable bugs.
Practice Exercise
Fix the bug in this code: val score = 100 score = 200 println(score)
val score = 100
score = 200
println(score)Quick Quiz
Which keyword declares a read-only variable in Kotlin?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review