Variables in Kotlin
Variables in Kotlin allow you to store and reuse data throughout your program. You can think of them as containers for holding information, such as numbers, text, or even results from calculations.
There are two main types of variables in Kotlin:
- var – Mutable (can change).
- val – Immutable (cannot change).
1. Mutable Variables (var)
A variable declared with var can be changed after it's initially assigned. This is useful when the value is expected to update during the program.
Example:
fun main() {
var score = 50
println("Initial score: \$score") // Output: Initial score: 50
score = 80 // Changing the value
println("Updated score: \$score") // Output: Updated score: 80
}
Explanation:
- We declare a variable
scoreusingvarand assign it the value50. - Later, we change the value of
scoreto80. This is possible becausevarallows the value to be modified.
2. Immutable Variables (val)
A variable declared with val cannot be changed once it’s assigned. This is useful when you don’t want the value to be modified accidentally.
Example:
fun main() {
val pi = 3.14
println("Value of pi: \$pi") // Output: Value of pi: 3.14
// pi = 3.14159 // Error! Can't change the value of 'pi'
}
Explanation:
- We declare a variable
piusingvaland assign it the value3.14. - If we try to change the value of
pi, Kotlin will give an error becausevalmakes the variable immutable.
When to Use var and val
- Use
varwhen you expect the value to change during the program. Example: a score that updates in a game. - Use
valwhen you know the value will not change. Example: a constant value likepior a configuration setting.
Benefits of Using val:
- Prevents accidental changes to important values.
- Helps make your code more predictable and easier to debug.
