I know that we can use the “var” keyword for defining variables in Kotlin:
var foo = 3
The latest java update (java 10) also introduces the “var” type:
var bar = new int[]{1, 2, 3}; // int[] bar = {1, 2, 3}
My question is, what is the difference of the use of “var” between these languages?
Kotlin uses two different keywords to declare variables: val and var . Use val for a variable whose value never changes. You can't reassign a value to a variable that was declared using val . Use var for a variable whose value can change.
The var keyword of Java 10 is similar to the auto keyword of C++, var of C#, JavaScript, Scala, and Kotlin, def of Groovy and Python (to some extent), and the : = operator of the Go programming language. One important thing to know is that even though var looks like a keyword, it's not really a keyword.
1. The variables can be mutable and immutable. This can also be done in Java (marking variables as final if we don't want it to be modified), but in Kotlin it is much less verbose and much more used: In Kotlin immutable values are preferred whenever possible.
Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
Their meaning is very different, even if the syntax in the basic case var x = ...
ends up being the same:
var
in Kotlin means "this is a mutable variable", and can be used both when type is inferred and when it's explicit: var x: String = ...
;
var
in Java means "this is a variable with inferred type", and can be used both for mutable and final
variables.
var
in Java can only be used for local variables; var
in Kotlin is used for properties as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With