1

I'm a beginner programmer working within a mixed Java/Scala codebase. I have a implicit class in Scala that provides extensions to a class within a third-party dependency. The implicit class is as so:

object ThirdPartyClassOps {
  implicit class ThirdPartyClassOps(val tp: ThirdPartyClass) extends AnyVal {
    ...
    def generateKey(): String = {
      tp.getId + "-" + tp.getOtherString
    }
  }
}

Where generateKey is the method I am interested in. My Java class where I'd like to call generateKey is as so:

public class MyJavaClass {
  ...
  public static boolean thirdPartyClassIsValid(ThirdPartyClass tp) {
    ...
    // Generate tp key here.

  }

}

My beginner's understanding of JVM languages indicates that it should be possible for me to call generateKey from my Java class. Searching for answers has led me to examples such as here where calling said Scala method has a simple solution. When I attempt to call it however using String myKey = ThirdPartyClassOps.ThirdPartyClassOps(tp).generateKey(); or String myKey = ThirdPartyClassOps$.MODULE$.ThirdPartyClassOps(tp).generateKey(); as suggested by the StackOverflow answer and IntelliJ's auto-suggest, I run into "error: cannot find symbol" error when attempting to build:

.../MyJavaClass.java:33: error: cannot find symbol
             String myKey = ThirdPartyClassOps$.MODULE$.ThirdPartyClassOps(tp).generateKey();
                                                                              ^
   symbol:   method generateKey()
   location: class ThirdPartyClass

Given the implicit class definition in Scala, how can I call my implicit class method within my Java class?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
hpabst
  • 406
  • 3
  • 6
  • 3
    Try `new ThirdPartyClassOps$.ThirdPartyClassOps(tp).generateKey()` – user Jun 05 '20 at 21:19
  • 3
    If you have a mixed project and common recommendation is to write java interfaces and stick with that for the interop. You will lose most of the scala features, but well you actually already lose them by mixing it with java. – Luis Miguel Mejía Suárez Jun 05 '20 at 21:22

0 Answers0