Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages/Drawbacks of "var" in Java 10 [closed]

Tags:

java

java-10

AFAIK, var is not keyword in Java. It is reserved type name. I wonder that in what circumstances we should use/avoid it. Are there principles about its usage?

import java.util.HashMap;

public class Test {
    public static void main(String[] args) {
        var x = new HashMap<> (); // legal
        var y = new HashMap<String, Integer>(); // legal

        var z = "soner"; // legal
        System.out.println(z);

        var umm = null;  // xx wrong xx //
        var foo; // xx wrong usage without initializer xx //

        var var = 5; // legal

    }
}
like image 475
snr Avatar asked Nov 28 '22 00:11

snr


1 Answers

I know one reason, that we actually use in our project. Whenever there is a variable that is "big" we replace it with var. For example:

 public void test(){
     CreateEmailEsignTransactionAsync job = new CreateEmailEsignTransactionAsync(... some input);

     // vs 
     var job = new CreateEmailEsignTransactionAsync(... some input)
 }

I find the second example a lot more readable, and this is how we mainly use it.

There is another example where this could be used (but I am not using it so far). Previously this was possible via chaining only for lambda expressions for example, as this would be a type known by the compiler only - they could not be declared.

 public void test() {
        var test = new Object() {
            public void go() {

            }
        };

        test.go();
    }
like image 130
Eugene Avatar answered Dec 04 '22 21:12

Eugene