Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
  }
}
like image 288
dstibbe Avatar asked Oct 22 '14 20:10

dstibbe


1 Answers

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());
    }
}
like image 119
Sergii Lagutin Avatar answered Oct 02 '22 17:10

Sergii Lagutin