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?

2
  • 3
    Try new ThirdPartyClassOps$.ThirdPartyClassOps(tp).generateKey() Commented Jun 5, 2020 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. Commented Jun 5, 2020 at 21:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.