Design Converter
Education
Last updated on Dec 11, 2024
Last updated on Dec 11, 2024
If you're new to Kotlin or just brushing up on your skills, understanding these two keywords is a must! They play a big role in how you handle variables in your code.
In this blog, we’ll break down Kotlin val vs var, explain how they work, and help you choose the right one for every situation.
Let’s make coding in Kotlin simpler and more fun! 🚀
In Kotlin, the val keyword declares read-only variables, meaning the value assigned cannot be changed once initialized. Think of val as a final variable in Java. On the other hand, the var keyword declares mutable variables, meaning their values can be modified after declaration.
Here’s how you declare variables in Kotlin:
1val x: Int = 10 // Read-only variable 2var y: String = "Hello" // Mutable variable
Both val and var can be used as local variables, class properties, or even within functions. The key difference lies in mutability: val means immutable, while var allows reassignment.
When you use val, you are creating a variable whose value cannot be changed after it is initialized. This makes it functionally equivalent to a final variable in Java.
Immutable: The value assigned to a val property cannot be reassigned.
Reference vs. Object Stored: While the reference of a val variable cannot change, the contents of the object stored may still be mutable.
Used for Constants: If the value won’t change during the program’s lifecycle, declare it with val.
1val name: String = "Kotlin" 2// name = "Java" // Compiler error: Val cannot be reassigned 3 4println(name) // Output: Kotlin
The var keyword is used when you need a variable whose value can be updated. Unlike val, the compiler imposes no restrictions on reassignment for var.
Mutable: You can reassign a new value to a var variable.
Best for Local Variables: Use var in situations where you expect the variable to change during runtime.
1var counter: Int = 0 2counter += 1 // Allowed 3println(counter) // Output: 1
The fundamental difference is mutability:
• val means the variable is immutable and its value cannot be reassigned.
• var allows reassigning new values to the variable.
Aspect | val | var |
---|---|---|
Mutability | Immutable (cannot be changed) | Mutable (can be reassigned) |
Reassignment | Not allowed | Allowed |
Object Stored | Only the reference is immutable | Both reference and value can change |
Similar to in Java | final variable | General variable |
Common Use Cases | Constants, read-only properties | Changing values like counters or states |
Thread Safety | Safer due to immutability | Requires caution in multithreaded code |
Syntax Example | val x = 5 | var y = 10 |
• Immutable variables: Use val when the variable’s value will not change.
• Compile-Time Constants: Ideal for storing values like configuration keys.
• Default for Safety: Prefer val unless you explicitly need mutability.
1class Person(val name: String, val age: Int) 2 3val john = Person("John", 30) 4// john.age = 31 // Compiler error
• Changing Values: Use var for counters, accumulators, or other variables that are expected to change.
• Local Variables in Functions: Common in loops and conditions.
1fun main() { 2 var sum = 0 3 for (i in 1..5) { 4 sum += i 5 } 6 println(sum) // Output: 15 7}
Even though val ensures that the reference cannot be changed, the object stored in the reference might still be mutable.
1val numbers = mutableListOf(1, 2, 3) 2numbers.add(4) // Allowed, as the object stored is mutable 3println(numbers) // Output: [1, 2, 3, 4]
In contrast, a var reference can point to a completely new object:
1var list = mutableListOf(1, 2) 2list = mutableListOf(3, 4) // Allowed 3println(list) // Output: [3, 4]
Overusing var can make your Kotlin code harder to understand. Instead, use val wherever possible to ensure immutability.
If you’re creating a constant or a property that cannot be changed, always prefer val.
Kotlin encourages the use of immutable variables for better thread safety and predictability. Following this principle makes your code easier to debug.
Which one should you choose: Kotlin val or var? 🤔 It all depends on your use case!
In Kotlin, val is perfect when you want a value to stay constant, ensuring immutability and safer code. On the other hand, var is the go-to choice when you need flexibility to reassign values. Both have their unique roles, and knowing when to use them makes your Kotlin journey smoother. 🚀
So, as you write your next line of Kotlin code, think about what your variable needs to do. Is it a steadfast companion or a dynamic changemaker? The answer will guide your choice between val and var.
Happy coding! 💻🎉
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.