“var” in java 10 and kotlin

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 :
  1. Their meaning is very different, even if the syntax in the basic case var x = ... ends up being the same:

    1. 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 = ...;

    2. var in Java means "this is a variable with inferred type", and can be used both for mutable and final variables.

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