3

Let's say I have something like this:

var x : String = "str"

// here do some with x, but not assign new value to it

Then Android Studio tells me that x should be declared with val, not var.
I know what's the difference between var and val.
If I don't need to assign value to x it could be val.
But does it make any difference at runtime?
When I declare variable with val instead of var, is it somehow faster?

This is not duplicate! I am asking about performance, not about difference in meaning.

J K
  • 632
  • 7
  • 24
  • it's more language level enhancement - it's recommended to use final in java whenever where possible, but no one follows that recommendation. You make big favor to one who will read the code in future and of course don't forget about nullable types – Viktor Yakunin Mar 04 '18 at 11:31
  • And yes, you better use val instead of var - you can change declaration when needed – Viktor Yakunin Mar 04 '18 at 11:32
  • When Android Studio suggests that you declare a variable with val instead of var, it is indicating that the variable doesn't need to be mutable and can be declared as read-only. This suggestion helps enforce immutability where possible, which can lead to more robust and maintainable code. – arjun Jun 14 '23 at 09:26

1 Answers1

7

val is like a final variable in java. Use it if you wont change the value. val is immutable.

var is a normal variable that changes its value. var is mutable.

You should make x val because the programmer who's reading the code will know that's it's a final variable. Using var/val doesn't make any difference in performance.

denvercoder9
  • 2,979
  • 3
  • 28
  • 41