-
Notifications
You must be signed in to change notification settings - Fork 22
Using val and var in Kotlin
Devrath edited this page Feb 10, 2024
·
1 revision
![Screenshot 2024-02-10 at 2 34 40β―PM](https://private-user-images.githubusercontent.com/1456191/303826251-13871611-648b-4f1f-abc9-8b082f79df63.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjQ2MTIyNzQsIm5iZiI6MTcyNDYxMTk3NCwicGF0aCI6Ii8xNDU2MTkxLzMwMzgyNjI1MS0xMzg3MTYxMS02NDhiLTRmMWYtYWJjOS04YjA4MmY3OWRmNjMucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDgyNSUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA4MjVUMTg1MjU0WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NWNkOGFhYTAxMDgzYzE3MDU5ODBkYTM4MWIxMmFmYjM1MjgyYTM0ZjYxNmNlNzMzMTgxZGNiMDdjOGViM2E0ZSZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.KsA_usMU1l9gjW9tRW_GfNOvL85zopdLq_0vBrwbKIM)
In Kotlin, val
and var
are keywords used to declare variables, but they have different characteristics in terms of mutability.
-
val (Immutable Variable):
-
val
is short for "value." - Variables declared with
val
are immutable, meaning their values cannot be changed once they are assigned. - They are similar to final variables in Java or constants in other languages.
Example:
val pi = 3.14 // pi cannot be reassigned to a different value
-
-
var (Mutable Variable):
-
var
is short for "variable." - Variables declared with
var
are mutable, meaning their values can be reassigned.
Example:
var count = 10 count = 20 // valid, as count is mutable
-
In general, it's a good practice to use val
whenever possible, as immutability helps make the code more predictable and easier to reason about. Use var
when you need to change the value of the variable during its scope.
Here's a simple guideline:
- Use
val
by default. - Use
var
only if you need to change the value during the execution of the program.
Immutable variables (val
) contribute to more predictable and safer code, as they prevent accidental reassignments and side effects.