What is the var difference between Kotlin and Java?

11

With the release of Java 10, the possibility of using var was introduced:

var list = new ArrayList<String>();

I have already seen what is the difference between

asked by anonymous 25.05.2018 / 22:12

2 answers

10

Basically in Kotlin it can be used in type members and in Java it can only be used for local variables, just as in Kotlin it can also.

Probably this is one of the reasons that the Kotlin compiler is slow, inferring type in members is much more complicated.

Despite having different small details, they work equally well.

In Java final can be used to have effect similar to val of Kotlin.

It works as well analogue to C # too.

    
25.05.2018 / 22:24
10

var in Java has come to reduce the verbosity of the language a little. The compiler does type inference and prevents you from having to repeat the type in some situations.

Instead of writing:

ByteArrayOutputStream bos = new ByteArrayOutputStream();

Now you can write:

var bos = new ByteArrayOutputStream();

It is a feature that already existed in several languages, and now Java has decided to adopt.

An important observation is that it can only be used in local variables (within methods in the initiator block, such as enhanced for loop index, lambdas expressions, and local variables declared within the traditional for

    
25.05.2018 / 22:31