Proposal: Allow a single-parameter method to be used as an infix operator

Elias Ross genman at noderunner.net
Thu Apr 23 10:44:46 PDT 2009


AUTHOR(S): Elias Ross

OVERVIEW

FEATURE SUMMARY: Allow a single-parameter method to be used as an
infix operator. Expressions like "object1.method(object2)" could be
replaced with an easier-to-read expression "object1 method object2".
This allows for easier to read code such as "a equals b" instead of
"a.equals(b)". This idea borrows from Scala, although this proposal
limits the complexity.

MAJOR ADVANTAGE: Since Java does not allow for operators or operator
overloading, all idiomatic expressions, such as "a.equals(b)", or
"a.contains(b)" must be written using dots and parenthesis.

MAJOR BENEFIT: Improvement in clarity for many idioms.

MAJOR DISADVANTAGE: Obviously, code with this feature would look quite
different than code without. Thus, I imagine it would look quite
inconsistent to have both used in the same codebase. Also, it's not
clear why, in the case of "object1 equals object2", when "object1" was
null, a NullPointerException should be thrown. It also may seemingly
collide with the "instanceof" operator.

It would potentially encourage increased use of single parameter methods.

ALTERNATIVES: None.

EXAMPLES

SIMPLE EXAMPLE:

boolean eq = "a" equals "b";

ADVANCED EXAMPLE: Show advanced usage(s) of the feature.

"abc" substring 1 matches "b."; // true
(new BigInteger(10) divide new BigDecimal(2)).longValue(); // 5

// The following would not compile
"abc" substring(1,2) equals "b";

DETAILS

SPECIFICATION:

Modification to
http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html

Expression2Rest:
	{Infixop Expression3}
+	{Identifier Expression}
	Expression3 instanceof Type

The "Identifier" refers to a single parameter method belonging to a
class or instance, and "Expression" here evaluates to the argument
passed to this method.

COMPILATION: The compiler would treat the expression as a method call.

TESTING: Testing would be done to validate the grammar and conflict
with the "instanceof" operator.

LIBRARY SUPPORT: None.

REFLECTIVE APIS: None.

OTHER CHANGES: None.

MIGRATION: Code needs no migration. However, it might be nice to have
a tool to "clean up" existing code.

COMPATIBILITY

BREAKING CHANGES: None.

EXISTING PROGRAMS: Should continue to work.

REFERENCES

EXISTING BUGS: Unknown.

URL FOR PROTOTYPE (optional):



More information about the coin-dev mailing list