|
|
|
|
|
by Nevermark
928 days ago
|
|
I have often used a Java utility class of static inferring generic constructors: public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); }
public static <K,T> HashMap<K,T> newHashMap() { return new HashMap<K,T>(); }
So code can look simpler, but just as clear: import static GenericConstructors.*;
...
ArrayList<String> names = newArrayList();
HashMap<String, List<int>> hashmap = newHashMap()
The "x := 10" example is one reason it feels safer to me to declare the variable type, and infer the constructor types, than the other way around.-- What would resolve this whole issue is standardized editor/IDE visualization support for showing all inferred types, just one toggle button/key away. Inferred types simplify writing code. But when reading code, why should we have to mentally emulate the language's inference algorithm? It is, by definition, supposed to be automating that for us. |
|
Your static utility functions save only 2 characters, but will add massive confusion for other developers.
or even better just use var: Those static functions are neither simpler nor cleaner. Don’t do this.