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?
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.