Operator overloading is available in an number of languages. Java has very limited operator overloading in it's support for the + operator for String types.
We can draw on the different ways other languages support operators, but can we have an implementation in Java that uses conventions that Java already uses?
Get, Set and Put Operations
A common example of operator overloading for collections is using the array notation a[b] to access the collection itself. When getting this is straight forward as both List and Map have a get method and this is consistent with the JavaBean getXxx() naming convention.
List<String> text = ... String s = text; // text.get(2); Map<String, MyType> map = ... MyType mt = map["Hello"]; // map.get("Hello") MyType mt = ... String xxx = ... String s = mt[xxx]; // mt.getXxx();
When it comes to setting a value based on an index or key, we have List.set(), Map.put() and setXxx() from JavaBeans. We could go three way to resolve this.
- Add a set method to Map.
- Use a convention which looks for a set or put method and complains if there is both.
- Default to set() but add an annotation which override it to put().
- We add a new special method to all collections for setting.
The simplest option to demonstrate is where the compiler chooses either set or put, though this is unlikely to be the best option.
text = "Hi"; // text.set(2, "Hi"); map["Hello"] = "World"; // text.put("Hello", "World"); mt[xxx] = "Updated"; // mt.setXxx("Updated");
The add operations are more interesting as it could be used in combination.
List<Integer> nums = AtomicInteger ai = nums += 5; // nums.add(5); ai += 5; // ai.addAndGet(5); nums += 5; // is it thread safe? mt[xxx] += 5; // mt.addXxx(5);
The last example has the problem that a developer could unknowingly perform an unsafe operation on a thread safe collection. If this was mapped to...
nums.set(1, nums.get(1) + 5)); // not thread safe This is not thread safe. Instead, we could map this to a lambda function. nums.update(1, x -> x + 5); // could be thread safe
This could be made thread safe by the underlying List.
Similarly for Map, you can call compute
map["Hello"] += " !!";
map.compute("Hello", (k, v) -> v + " !!");
It may be possible to add operator support for object types with very little changes to existing code. You could use existing conventions though you might find that the use of annotations is needed in some cases for more explicit control on how this works.