What is the difference of var between Kotlin and Java?

Asked

Viewed 214 times

12

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

var list = new ArrayList<String>();

I’ve seen the difference between val and varin Kotlin, but I would like to know more about the var, with regard to Java.

2 answers

11


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

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

Although they have little different details, they work equally.

In Java the final can be used to have similar effect to val kotlin.

Forms analogous to C# also.

10

var in Java came to reduce the verbosity of the language a little. Compiler makes type inference and prevents you from having to repeat type in some situations.

Instead of writing:

ByteArrayOutputStream bos = new ByteArrayOutputStream();

Now it is possible to 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 initializer block, such as Enhanced for loop index, Lambdas Expressions, and local variables declared within the traditional)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.