Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“var” in java 10 and kotlin

Tags:

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?

like image 350
gldanoob Avatar asked Mar 29 '18 02:03

gldanoob


People also ask

What is a VAR in Kotlin?

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.

What is the equivalent of VAR in Java?

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.

In which way variable declaration in Kotlin differs from Java?

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.

Is VAR available in Java 11?

Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.


1 Answers

  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.

like image 105
Alexey Romanov Avatar answered Oct 24 '22 16:10

Alexey Romanov