How to Declare Variable in Kotlin: Syntax and Examples
In Kotlin, you declare a variable using
val for read-only variables or var for mutable variables, followed by the variable name and optional type. For example, val name: String = "John" declares a constant string variable.Syntax
To declare a variable in Kotlin, use either val or var. val creates a read-only variable (like a constant), and var creates a variable that can change. You write the variable name, optionally specify its type with a colon, then assign a value with =.
- val: immutable variable (cannot change)
- var: mutable variable (can change)
- variableName: the name you choose
- type: optional, Kotlin can often guess it
- value: the data you assign
kotlin
val variableName: Type = value
var variableName: Type = valueExample
This example shows how to declare both a read-only and a mutable variable. It prints their values and changes the mutable one.
kotlin
fun main() {
val name: String = "Alice" // read-only variable
var age: Int = 30 // mutable variable
println("Name: $name")
println("Age: $age")
age = 31 // changing mutable variable
println("New Age: $age")
}Output
Name: Alice
Age: 30
New Age: 31
Common Pitfalls
One common mistake is trying to change a val variable, which causes an error because it is read-only. Another is forgetting to initialize a variable or giving it a wrong type.
Always use var if you plan to change the variable later, and initialize variables before use.
kotlin
fun main() {
val constant = 10
// constant = 20 // Error: Val cannot be reassigned
var number: Int
// println(number) // Error: Variable 'number' must be initialized
number = 5
println(number) // Correct usage
}Output
5
Quick Reference
| Keyword | Meaning | Can Change? | Example |
|---|---|---|---|
| val | Immutable variable (constant) | No | val pi: Double = 3.14 |
| var | Mutable variable | Yes | var count: Int = 0 |
Key Takeaways
Use
val for variables that should not change after assignment.Use
var for variables that need to be updated later.Kotlin can often infer the variable type, so specifying it is optional.
Always initialize variables before using them to avoid errors.
Trying to reassign a
val variable causes a compile-time error.