What the ****? Operator Overloading in Java

Daniel Winterstein

@winterstein

CTO at SoDash

C++

Algol

MyVec MyVec::operator+(MyVec vec)
        { /* code */ }

 

Examples of Madness

Custom Operators from Scala Graph project:

1 ~ 2 % 5     Creates an edge with weight 5
~%#+           Create key-weighted labeled undirected edge

~%+#           Create weighted key-labeled undirected edge

Make Array + Array mean bitwise xor of the elements via implicit conversion

implicit class ByteArrayOps(private val a1: Array[Byte]) extends AnyVal {
  def + (a2: Array[Byte]): Array[Byte] =
    (a1 zip a2).map { case (x, y) => (x^y).toByte }
}

James Gosling →

Java →

Old school    

vestments →

So How Do We Do It?

  • You can alter the compiler:

    • Javac 7 has annotation processors

    • Javac 8 has plugins

  • & Artem Melentyev has: https://github.com/amelentev/java-oo

  • With plugins for Eclipse, IntelliJ, and NetBeans

Why is overloading great?

  • Concise
  • Clear: Let the maths shine through

Why is overloading dubious?

 - Changes the language.

 - Precedence: no right solution for parsing.

   E.g. We know how to parse

          a + b * c

   but how should we parse

          a ¬ b " c

 - But Java-OO is limited: no custom operators

Examples of Java-OO...

What the ****? Operator Overloading in Java

By winterstein

What the ****? Operator Overloading in Java

  • 43