dstibbe
dstibbe

Reputation: 1697

Using vals from scala package object in java

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());
  }
}

Upvotes: 5

Views: 3204

Answers (1)

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

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());
    }
}

Upvotes: 7

Related Questions