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

17

u/_INTER_ Mar 09 '16

How will this deal with code like:

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

I always wondered why they've choosen to abbreviate the RHS instead of the LHS (in Java 7 I think). Clear me up please.

9

u/codebje Mar 09 '16

The proposal has an example for just such a case:

var lst = new ArrayList<String>();

The inferred type will not be List<String>, it'll be ArrayList<String>, but thanks to polymorphism you can use that anywhere you'd want to use a List<String> anyway.

2

u/_INTER_ Mar 09 '16

I was more thinking about how it will invere

var list = new ArrayList<>();    

14

u/bjzaba Mar 09 '16

That would require a smarter type reconstruction algorithm, like Hindley-Milner. That's probably a step too far for the conservative Java committee.

3

u/Sean1708 Mar 10 '16

The day Java gets HM is the day I walk around town with "The End Is Nigh" hanging around my neck.

2

u/csman11 Mar 10 '16

I remember seeing an SPJ talk where he mentioned that HM cannot be used in OO languages because of subtyping (he didn't explain this). But that obviously will never happen in Java. Someone correct me if I'm wrong. I don't know a lot about type inference.

The video was something like "classes but not as you know them" on channel 9 and was about type classes. The above was briefly mentioned in the last few minutes.

Edit: title was "classes, jim, but not as we know them"

1

u/kqr Mar 10 '16

Subtyping does wreck full inference, but limited (still somewhat useful) inference is still possible. Edward Kmett once summarised it as "it works great until the point where you really need it, when it breaks down."

→ More replies (1)

4

u/codebje Mar 09 '16

If it was using full type inference, it'd examine the use sites of list to infer what the contained type should be.

But I think that the scope of this proposal doesn't go so far, and that would be an error.

3

u/im-a-koala Mar 10 '16

I'm not convinced that's even a good idea in the first place, honestly. I would be rather confusing to have the type of a local inferred by future uses of the local.

2

u/codebje Mar 10 '16

It would be something like this:

public List<String> greet() {
    var list = new ArrayList<>();

    list.add("Hello, ");
    list.add("World");
    return list;
}

Let's just look at the expression return list here. Its abstract syntax tree will be a Return node with list as the expression to return, and the type of the return expression must be assignable to List<String>. Whatever type list has, it must now satisfy assignability to List<String> for the types to unify.

If we also look at var list = new ArrayList<>();, we know the right-hand side of the expression has a type of ArrayList<a> where a is an unresolved type, and thus the left-hand side must be of a type which is assignable from ArrayList<a>.

At this point the compiler can reconcile that List<String> must be assignable from ArrayList<a>; a List is assignable from an ArrayList, so that's fine, but the only thing which a can be for this to compile now is String: the signature for List<String> is not variant in its generic type.

A type inferencing algorithm has some choice here: it can work out the most general type which suits, or the most specific type, or any type which satisfies all known conditions. AFAIK most algorithms go for the most general type, and narrow it as needed, so let's go for that.

What's the most general type which can be assignable to both a List<String> and an ArrayList<String> ? Well, it's just List<String>, so therefore the type of list should be List<String>.

We check that against the remainder of the AST, notably the expressions list.add("Hello, ") and list.add("World"). These require a method add(=String) on list, using made-up syntax to express that the method needs an argument type assignable from String. This checks fine, as String is assignable from String in the signature add(E ...) where E is String.

All that magic happens under the hood, but when you read that, it's pretty obvious that the type of list must be something which can hold an ArrayList, and the ArrayList's generic argument must be String, because you've gotta be able to assign the ArrayList in, add some Strings to it, and return it as a List<String>.

It's my opinion that the code above has all the information a programmer needs to understand what's going on. Whether list is typed as List<String> or ArrayList<String> doesn't really matter, because (a) the object it refers to is definitely going to be an ArrayList<String> no matter the variable's type, and (b) it'll be returned as a List<String> no matter the variable's type. There's no ambiguity in the meaning of the code, and some boilerplate declaration of "obvious" types is removed.

Static typing really shines when it gives you all the compile-time guarantees of correctness that a static type system allows, yet doesn't require wads of tedious boilerplate when it's "obvious by looking at it".

Being freed from worrying about intermediate types is already a great win for Java 8's expressivity, a similar freedom from worrying about the type of transient variables is something I welcome :-)

3

u/normalOrder Mar 10 '16

This is a great explanation, but it also demonstrates a huge reason why it won't happen: the Java designers assume most Java programmers are too dumb to understand.

some users imagine type inference to be a form of mind reading, rather than an algorithm for constraint solving

4

u/im-a-koala Mar 10 '16

Yeah, and I think that example is awful. Okay, it looks cute for a very small, unrealistic function with a single local and only adding literals, but once you get 20-30 lines, throw in more than one local, and add things to the list that are returned from other functions, it quickly becomes very, very difficult to reason about.

6

u/Sean1708 Mar 10 '16

I dunno, it's working out pretty well in Rust.

2

u/kqr Mar 10 '16

Yes, and that's why, in languages with full type inference, it's recommended to write out the full type for things that are in large scopes. You really only skip it for things that are in scope for up to 8 something lines.

→ More replies (1)
→ More replies (1)

2

u/Eirenarch Mar 10 '16

This won't compile. You will use

var list = new ArrayList<String>();

instead. There is no benefit from the diamond syntax in the presence of var.

→ More replies (5)

8

u/henk53 Mar 09 '16

I always thought that it was simply an extension of the earlier limited type inference that already existed for generic methods (since Java 5).

In the generic method case you do:

List<String> lst = someObject.someMethod();

Since someMethod is defined generically there's nothing to abbreviate here at the RHS. The method is just a generic method with <T> in front of it returning a List<T>.

You could see the constructor as a special method, so in pseudo code if you changed it to:

List<String> lst = new ArrayList.ArrayList();

It may become clear why the RHS was abbreviated. Additionally, it's only because of legacy and the concept of raw type that we were never able to write:

List<String> lst = new ArrayList();

Since that syntax was already taken and retrofitted for the introduction of raw types, instead of "simply" be upgraded (like methods were) to have limited generic type shortening.

7

u/s888marks Mar 09 '16
List<String> lst = someObject.someMethod();

Assuming that someMethod is generic, this really is an abbreviation for

List<String> lst = someObject.<String>someMethod();

The type inference for generic methods works so well that this syntax is rarely necessary, so rare that many people don't even know this syntax exists.

1

u/henk53 Mar 09 '16

True, although I've needed to use it on a couple of occasions though. In a select few cases because of a compiler bug where the type should have been inferred but wasn't.

1

u/im-a-koala Mar 10 '16

It comes before the method name in Java? Huh. In C# it comes after, like:

List<String> lst = someObject.someMethod<String>();

5

u/immibis Mar 10 '16

Probably chosen because that's harder to parse, because the compiler doesn't know whether String is supposed to be a type or a variable until it gets to the >.

(Consider:

class X {
    int getValue;
    <T> int getValue() {return 5;}
}
X someObject = new X();
int String = 7;
int i = someObject.getValue<String?1:0;
int j = someObject.getValue<String>();
//                                ^

and don't complain about the bad naming, because that is legal in Java)

1

u/kcuf Mar 10 '16

That's what Scala does as well

List[String] list = someObject.someMethodString

or, more commonly seen as

List[String] list = someObject.someMethod[String]

1

u/normalOrder Mar 10 '16

I think you mean

val list = someObject.someMethod[String]

Or if you really want the type annotation

val list: List[String] = someObject.someMethod[String]
→ More replies (1)

1

u/irarandomdude Mar 10 '16

It won't, and doesn't need to. It's the same in Scala, you'd have val lst: Seq[String] = ArrayBufferString

1

u/[deleted] Mar 10 '16

val lst: List<String> = new ArrayList()

;)

→ More replies (14)