Who wants Indexer as the next EoD feature?
We all know the Java Collections Framework - Collection, List, Set, Map are used in almost every Java application. We also know that operator overloading in not available in Java, something that has caused a huge debate over the years, especially after C# came out and had it as a feature.
In fact, just today Daniel Pitts posted something about it under his “almost useful” tag. In that, he obviously mentions the convenient square brackets operator
map[“key”] or list[1] where map is a Map instance and list is a List instance, of course.
Some history about EoD
When Java 5 came out, many ease of development (EoD in short) features were introduced. One of them was the “foreach” loop - a syntax for iterating over arrays and collections from the collections framework easily and, as an extra effect, in a standard way. This was accomplished by extracting the iteration interface out of the Collection interface, now namedIterable. Everything that implements the Iterable interface could be used in a “foreach” loop (which is, by no coincidence, the implemented interface by my Yielder class, which is a virtual collection).
It makes sense for another EoD interface to come out: the Indexer interface. This interface could be a simple interface which would allow for [ ] operators to be used through code. This shouldn’t be an issue for the operator overloading debate: The square brackets interface can hardly be used for operator abuse (with the exception of functor objects, but without the ability to have multiple parameters it would be a pretty lame usage), and if operator overloading does infiltrate the Java language, the compiler feature could be replaced with something that uses that language feature.
The details about Indexer
The Indexer interface could be as simple as:public interface Indexer<K, V> {
void put(K key, V value);
V get(K key);
}
And now, together with the EoD compiler feature, every call such as indexer[key] = value could be compiled to indexer.put(key, value), and value = indexer[key] could be compiled to value = indexer.get(key). This shouldn’t and couldn’t be hard to do in compile time, especially seeing that the [ ] operator is currently reserved only for array instances.
This feature could obviously be used for some interesting new classes, but it would be even more relevant with current collections’ interfaces, such as Map<K, V> implements Indexer<K, V>, and perhaps the less obvious but as important List<T> implements Indexer<Integer, T>, allowing us to use collections the way they were meant to be used (and are indeed used already in many other languages).
As always, I'm interested in hearing your opinion about it!
Comments (8)
get(int)defined inList, or some other reason? Also, it is unfortunate but might be necessary to create to interfaces, just to not create redundant methods (setvs.putin List, for example).