Is it possible to overload operator += directly in Scala? It might be useful for some complex types, where a += b may have more efficient and simpler implementation that a = a + b.
The case I encountered recently is I am providing operators for Vector3f
from jMonkeyEngine (com.jme.math). A natural implementation could look like:
import com.jme3.math.{Matrix3f, Vector3f}
object JMEMathOperators {
implicit class Vector3fMath(val a: Vector3f) extends AnyVal {
def - (b: Vector3f) = a subtract b
def + (b: Vector3f) = a add b
def * (b: Vector3f) = a mult b
def * (b: Float) = a mult b
def += (b: Vector3f) = a addLocal b
}
}
In spite of no compile errors, my +=
implementation is never called. The difference is not that important in this case, addLocal
efficiency is only marginally better than add
, but one can image there are some complex classes where the difference could be important.