5

I have a Scala package object with vals declared in it. So I can use common objects without each time importing all of them.

However, I'd like to use these definitions in Java also, however Java does not allow importing of anything called 'package' which is the name of the class created by Scala.

Is there a way around this, that I can have these package objects and import them into Java

Update Followed the accepted solution. However, added an intermediate class for readability:

package.scala:

package nl.mysoft.scalapackage

package object easy {
  val one = 1
}

Intermediate class:

package nl.mysoft.javapackage;

import nl.mysoft.scalapackage.easy.package$;`

public class EasyE {
  public static final package$ e = package$.MODULE$;
}

And usage:

package nl.mysoft.javapackage.usage;

import static nl.mysoft.javapackage.EasyE.e;

public class EasyTest {
  public static void main(String[] args) {
    System.out.println(e.one());
  }
}
1
  • I am trying something similar, but in my case one is not an val, but object. How to access it, can you help me? Tried to use your example, but it does not work. Commented Mar 6, 2019 at 12:45

1 Answer 1

7

Try this

ex.scala.package.scala:

package ex

package object scala {
  def one = 1
}

ex.java.Test.java:

package ex.java;

import ex.scala.package$;

public class Test {
    public static void main(String[] args) {
        System.out.println(package$.MODULE$.one());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thnx mate :-) Even I was facing this issue

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.