Advantages/Drawbacks of “var” in Java 10 [closed]

杀马特。学长 韩版系。学妹 提交于 2019-12-05 22:31:05

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();
    }

I can see one drawback to use var aka "Local type-inference":

var x = "A";
// String x
var y = getInstance(x);
//? y

In that context, you need to check the signature of getInstance(String) method to know what will be y type.

EDIT:

Since there is a discussion about the name of my variables not being really correct, let's use some real example then.

 var sDate = "20180426";
 var date = DateUtil.getDate(sDate);

What type is date ?

I could call

 public static java.util.Date getDate(String);
 public static java.sql.Date getDate(String);
 public static java.time.LocalDate getDate(String);

I don't believe the solution would be to use a full name either.

 var javaUtilDate
 var javaSqllDate
 var javaTimeLocalDate

So instead, in that case I would not use type inference

var sDate = "20180426";
LocalDate date = DateUtil.getDate(sDate);

Note: Can someone tell me if this require the import of LocalDate if I use var (note that I use a method in a different class, so I never had to declare LocalDate in this class).
I will answer myself if I find the time to install a JDK10.

You could use it for anonymous classes too, i.e. there is just no type to declare. E.g.

var r = new Runnable()
{
  int result1, result2;
  @Override public void run()
  {
    result1 = doStuff();
    result2 = doMoreStuff();
  }
}

makeSomething(r);
System.out.println(r.result1 * r.result2);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!