r/programming • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
250 Upvotes

395 comments sorted by

View all comments

Show parent comments

7

u/Radixeo Mar 09 '16

It would help keep the line length down. In this common example

ArrayList<String> foo = new ArrayList<String>();
var foo = new ArrayList<String>();

The second line is shorter, simpler, and it is still obvious what the type of foo is.

19

u/depressiown Mar 09 '16 edited Mar 09 '16

ArrayList<String> foo = new ArrayList<String>();

You shouldn't be doing this since 1.7 and should be using the diamond. The real comparison here is:

List<String> foo = new ArrayList<>();
var foo = new ArrayList<String>();

Without the left side, you have to move the generic type to the right, whereas with the current notation you can use the diamond since Java can infer the generic type on the right side from the left side.

Honestly, I don't see a lot of gain here. Lombok has val, which is similar, but limited, though it would be better if it were inherent to the language. That said, I like things being explicit so I am biased.

5

u/[deleted] Mar 09 '16

[removed] — view removed comment

6

u/depressiown Mar 09 '16

My point is that with val, Java won't be able to infer the generic type on the right side of the expression. You'll now have to define it, whereas you wouldn't with diamond, so long as the left side is explicit.

Using val will reduce the number of characters, but not by as much as you might think for objects with generics.

I'd argue that the diamond is not so narrow a use case as you might think, too, and that val hurts readability by making the left side non-explicit. Those are purely opinion, though.

→ More replies (2)

1

u/four024490502 Mar 09 '16 edited Mar 09 '16

and should be using the diamond.

I haven't programmed in Java for a while. What's the diamond?

Edit: Oops... my initial google search for 'java diamond' turned up a bunch of 'Java introduction printing a diamond pattern' tutorials. This explains it. I think my original point below still stands, though.

Doesn't that only expose List<String> as the interface for foo? What if I want to manipulate foo with a method defined in ArrayList<String>, but not specified in the List<String> interface?

4

u/depressiown Mar 09 '16 edited Mar 09 '16

Ignore the fact that I used the interface instead of the implementation class on the left side. It's just good practice since you abstract the implementation class, but sometimes won't work if the implementation class has some implementation-specific method you need. Either way, not relevant when discussing the diamond.

The diamond (<>) can be used if Java can infer the generic type of the implementation class (the right side of the expression). This is "new" in Java 7. For example...

List<String> foo = new ArrayList<String>();

... is exactly the same as:

List<String> foo = new ArrayList<>();

Since Java 7, it can infer the generic type on the right side is String. However, if Java can't infer it, it won't compile. For example, this method will not compile:

public List<String> foo() {
    return new ArrayList<>();
}

There is no left side. Java can't infer the generic type of "new ArrayList<>()". In this case, you would need ArrayList<String>(). Hopefully that makes a bit more sense about the diamond. You can Google it if I'm not explaining it very well.

My larger point is that right now, the diamond allows Java to infer the generic type. If we use something like var, that inference is gone and now you have to define the generic type on the right side. While you gain not having to define any type on the left, you now lose the ability to shortcut the generic type on the right side. Overall, it's a positive gain for number of characters, but it's not as large as people make it out to be for objects with generics... and to some, there's a loss of readability by not having the explicit type on the left.

3

u/s888marks Mar 10 '16
public List<String> foo() {
    return new ArrayList<>();
}

This compiles and works fine in 7 and beyond. The left-hand side is the return type of the method.

1

u/four024490502 Mar 09 '16

Thanks for taking the time to explain the diamond operator.

I guess my pedantry about declaring foo as an interface vs. the implementing class was about my understanding of the var keyword in C#, and my assumption about it operating similarly in Java. In C#, var becomes an instance of the most specific type determined by the right of the equals sign, so

var foo = new ArrayList<String>();

doesn't compile to the same thing as

List<String> foo = new ArrayList<>();

assuming Java implements the var keyword in a similar manner to C#.

1

u/depressiown Mar 09 '16

Not being familiar with C# at all, what does a method signature look like of something you pass this var to?

public void foo(var bar) { ... }

... or...

public void foo(ArrayList<String> bar) { ... }

I'd hope the former. Otherwise, what a nightmare that seems...

1

u/four024490502 Mar 10 '16

The former won't compile. You need to explicitly specify the type of a parameter in a method signature.

9

u/Helene00 Mar 10 '16

Another example:

var f = new SimpleBeanFactoryAwareAspectInstanceFactory();

instead of

SimpleBeanFactoryAwareAspectInstanceFactory f = new SimpleBeanFactoryAwareAspectInstanceFactory();

4

u/psxpaul Mar 09 '16

That example is clear, but even in the linked proposal, there are things like:

var stream = list.stream();

I'm guessing this could even lead further to:

var thing = foo.bar().processResults()

Where you have no idea what type 'thing' is just by looking at it.

8

u/codebje Mar 09 '16

True, but we do this already with lambdas. What type is the forst lambda in:

List<String> resultSummaries = list.stream()
    .map(a -> a.getResult())
    .map(r -> r.getSummaryLine())
    .collect(Collectors.toList());
return resultSummaries;

And more importantly, does it really matter given the compiler is statically checking your types anyway? If there's no type inferable (or it's ambiguous) there will be a compile error.

Compare with:

var results = list.stream().map(a -> a.getResult());
var summaries = results.map(r -> r.getSummaryLine());
var resultSummaries = summaries.collect(Collectors.toList());
return resultSummaries;

There's plenty of type inferencing going on in both cases. Explicitly calling out the type of the result, the type of the summary line, and the type of the list don't do a whole lot for improving understanding, IMO: it doesn't matter very much what type a result is, the intent is clear that we'll ask each result to produce its summary line, then collect those into a list.

→ More replies (1)

6

u/KagakuNinja Mar 09 '16

Coming from scala, val / var plus type inference is a godsend at reducing the visual clutter of code. Much of the time, we don't care what the exact type of "thing" is, we are going to pass it to another function, or return it.

The key with scala is that type annotations are optional. You use them when it is helpful for readability (or in some cases, to keep the type inference engine from getting confused, but that is rare IMO)

-1

u/geodel Mar 10 '16

Well for typical Java developer variables would be like

 ArrayList<String> fooListForUsersBasedInNorthernVirginiaOffice  = new ArrayList<String>();
 var fooListForUsersBasedInNorthernVirginiaOffice = new ArrayList<String>();

And now saving few char is hardly any improvement. Besides Java's hallowed IDEs means user never have to type.

3

u/[deleted] Mar 10 '16

Ok, for ArrayList<String> it's not a big deal.

What about when the type is like IObservable<Func<string,Func<IEnumerable<User>,IEnumerable<UserStatus>>>>

2

u/Helene00 Mar 10 '16

I have only seen that in C# and C++, people are generally not that keen on generics in Java.

3

u/[deleted] Mar 10 '16

Possibly because you have to type out those giant things...

3

u/yoden Mar 10 '16

That type would never pass my code review, var or not. This line of reasoning is one good reason to be opposed to var.

1

u/[deleted] Mar 10 '16

A higher order function wouldn't pass your code review?

I just made up some arbitrary thing, I'm sure you have a complicated generic type somewhere.

1

u/yoden Mar 10 '16

Higher order functions are fine, but Java isn't Haskell. The type system isn't strong enough. Using such a complicated type creates code that is very difficult to use or refactor. Var won't save you if you need to lift the calculation into a function.

1

u/mhixson Mar 11 '16

I would also question that in a code review. When I see a type like that, I immediately wonder why the author didn't write a class to encapsulate whatever it is doing.

1

u/antrn11 Mar 10 '16

That type would never pass my code review

Why not? What would be better?

→ More replies (1)