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
  • 590
  • 5
  • 19
  • 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

1 Answers1

6

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 it's 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,898
  • 3
  • 26
  • 39