Caleb :
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?
Alexey Romanov :
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 andfinal
variables.
var
in Java can only be used for local variables;var
in Kotlin is used for properties as well.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=428156&siteId=1