Var introduced in Java 10. It's convenient, but in some cases it can be addictive.
Sample code
var list = Set.of(BigDecimal.ZERO, BigDecimal.ONE);
//What is the type of this Collector?
var toList = Collectors.toList();
var list2 = list.stream().collect(toList);
//What is the type of list2? Correct answer: list<Object>
System.out.println(list2.get(0));
If all of the following conditions are met, it will be an Object type because the type cannot be determined. (1) There is no argument, or the generic type is not determined by the argument (2) No type argument is specified
However, avoidance itself is not difficult, and detection is not difficult. -Specify the type argument ・ Do not use var as before
Sample code 1(Specify the type argument)
var list = Set.of(BigDecimal.ZERO, BigDecimal.ONE);
//What is the type of this Collector?
var toList = Collectors.<BigDecimal>toList();
var list2 = list.stream().collect(toList);
//What is the type of list2? Correct answer: list<BigDecimal>
System.out.println(list2.get(0));
Sample code 2(Avoid using var as before)
var list = Set.of(BigDecimal.ZERO, BigDecimal.ONE);
Collector<BigDecimal, ?, List<BigDecimal>> toList = Collectors.toList();
var list2 = list.stream().collect(toList);
//What is the type of item?
System.out.println(list2.get(0));
However, this case is not just about "how to avoid it?" It seems that the difficult point is "whether to incorporate or not to incorporate? What kind of response policy should be unified?" For the new element called var, but by the way.
Recommended Posts