javascalascala-java-interop

Alias a Java method in Scala


Given a Java interface

interface Value {

  Value add(Value argument);

}

(since Java does not support symbols like + as method names), is it possible to define an alias method + to alias add such that, when the class is used from Scala one can write

  result = value1 + value2

instead of

  result = value1.add(value2)

or

  result = value1 add value2

The alias should apply automatically to all classes implementing the interface.


Solution

  • You can add external method extension via implicit class

    object ValueImplicits {
    
      implicit class ValueOps(val value: Value) extends AnyVal {
        def +(v: Value): Value = value.add(v)
      }
    
    }
    

    Now it can work like this

    import ValueImplicits._
    
    val v1 = new Value {}
    val v2 = new Value {}
    val v3 = v1 + v2
    

    You can avoid the import if you can create a companion object for interface Value in the same package.

    object Value {
    
      implicit class ValueOps(val value: Value) extends AnyVal {
        def +(v: Value): Value = value.add(v)
      }
    
    }
    

    Implicit resolution checks companion objects without any explicit import.