The following article describes what is the difference between a val and a var in Kotlin.
Basically, in Kotlin, we declare variables using val
and var
both. Accordingly, the main difference between the two is that val
declares an immutable variable (i.e., a variable that cannot be reassigned after it has been initialized). Whereas, var
declares a mutable variable (i.e., a variable that can be reassigned). The following example shows their usage.
val x = 10 // x is a val
x = 20 // This will result in a compile-time error, since x is a val and cannot be reassigned.
var y = 10 // y is a var
y = 20 // This is allowed, since y is a var and can be reassigned.
In fact, we prefer declaring a variable as a val
in Kotlin because it can help prevent unintended side effects and make the code easier to reason about. Also, immutable variables can help improve thread safety in concurrent programming.
However, there are times when you need to use a mutable variable. For instance, when you need to update the value of a variable in response to user input or other external events. In those cases, you would use a var
to declare a mutable variable.
In short, preferring a val
or a var
depends on the specific use case and programming requirements.
Further Reading
- Android
- Angular
- ASP.NET
- AWS
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Data Science
- Data Structures and Algorithms
- Deep Learning
- Django
- Dot Net Framework
- Drones
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- Machine Learning
- MEAN Stack
- MERN Stack
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Scratch 3.0
- Smart City
- Software
- Solidity
- SQL
- TypeScript
- VB.NET
- Web Designing
- XML