Hacker News new | ask | show | jobs
by hibbelig 2245 days ago
In Java, `var` comes in useful at times. For example:

    for (Map.Entry<SomeLongType, AnotherLongType> x : someMap) {
        final SomeLongType key = x.getKey();
        final AnotherLongType value = x.getValue();
        ...
    }
In the above code snippet, `var x` would have been very useful because the actual type just repeats information that can be found in the next two lines. Also, usually, I'll use more speaking names instead of `key` and `value`.

But if the body of the loop just refers to `x.getKey()` and `x.getValue()`, without extracting them into local variables, then it makes sense to put the exact `Map.Entry` type into the loop header.

2 comments

You can just use map.forEach and avoid the types in the next two lines too.
In java 10+

    for (Map.Entry<SomeLongType, AnotherLongType> x : someMap)    {
        final var key = x.getKey();
        final var value = x.getValue();
        ...
    }
Is valid.
I prefer to put "var" into the loop header because the combination of two types is hard to read. It's easier to read (for me!) when the type of the key and the type of the value are separated, like they are on the first two lines of the loop body.

    for (var x : someMap) {
        final SomeLongType key = x.getKey();
        final AnotherLongType value = x.getValue();
        ...
    }