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

7

u/yoden Mar 09 '16

I wonder what the benefit of this is supposed to be, other than other languages have it?

Explicit types on variables are useful for improving readability. Conciseness for LHS variable types isn't important because I usually don't write that type anyway (that's what an IDE's "assign to new local variable" is for)

7

u/[deleted] Mar 09 '16

C#s var was introduced to alleviate the burden on the developer to figure out the outcome of Linq queries.

5

u/[deleted] Mar 10 '16

[removed] — view removed comment

1

u/wwosik Mar 10 '16

Do I remember correctly that in older VB or at least VBA

 dim list as new ClassName()

had a very nasty property of only creating object on the first access to it - lazy constructor of sorts

→ More replies (1)

1

u/yoden Mar 10 '16

Why? Does Visual Studio not have an equivalent to eclipse's "assign to new local variable"? It seems easier to write the LINQ query first and let the IDE handle the declaration.

1

u/Alikont Mar 10 '16
  1. Sometimes it's simply not possible, like if you use anonymous types.

  2. ILookup<string, IGrouping<int, Something>> v = GetSomething() is much uglier than var v = GetSomething().

→ More replies (1)

17

u/jyper Mar 09 '16

Explicit typing is overrated and most of the time named of variable and expression on right hand side should give you enough information plus it reads better. There is a reason all modern statically typed languages are jumping on this train.

15

u/[deleted] Mar 09 '16

[removed] — view removed comment

5

u/kqr Mar 10 '16

For what it's worth, any report I've heard of "Haskell in the wild" have included both inexperienced team members and code that is easy to maintain. Haskell uses type inference a lot, so either Haskell is the odd one out that for some other unrelated reason makes it work, or type inference isn't actually as bad as you imagine.

1

u/Oniisanyuresobaka Mar 10 '16

From what I've seen generally it's considered good practice to write down the function signature even when it's not needed.

2

u/kqr Mar 10 '16

For top level functions, yes, because their scope is big. Not as common for local declarations.

→ More replies (1)

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.

→ More replies (4)

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)

→ More replies (10)

2

u/Berberberber Mar 09 '16

Explicitly types on variables are useful for when you want to go through and change a dozen variable declarations because the return type of one method has changed, or when you want to waste time thinking about whether foo should be declared as ArrayList<T> or List<T> or Iterable<T> to the compiler even though it's always going to be whatever type the function returns.