4 ms·
In Java, `var` comes in useful at times. For example: for (Map.Entry<SomeLongType, AnotherLongType> x : someMap) { final SomeLongType key = x.getK
by hibbelig 7y 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.
- enitihas 7y agoYou can just use map.forEach and avoid the types in the next two lines too.
- jerven 7y agoIn java 10+ for (Map.Entry<SomeLongType, AnotherLongType> x : someMap) { final var key = x.getKey(); final var value = x.getValue(); ... } Is valid.
- hibbelig 7y agoI 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(); ... }