Frage

how can i import a class from a simple java program in my scala script?

i have:

ScalaCallsJava.scala
hello/Hello.java
hello/Hello.class

the scala:

import hello.Hello

new Hello().hi("Scala")

the java:

package hello;

public class Hello {
    public void hi(String caller) {
        System.out.println(caller + " calling Java");
    }
    public static void main(String[] args) {
        (new Hello()).hi("Java");
    }
}

i have blindly tried a few different permutations (package or no, same dir etc) and i do have my java class, but i keep getting "not found" on the import.

War es hilfreich?

Lösung 2

i got this to work. maybe the scala can't be a script.

i have:

ScalaCallsJava.scala
hello/Hello.java

the scala:

import hello.Hello

object ScalaCallsJava {
  def main(args: Array[String]) {
    new Hello().hi("Scala")
  }
}

the java:

package hello;

public class Hello {
    public void hi(String caller) {
        System.out.println(caller + " calling Java");
    }
    public static void main(String[] args) {
        (new Hello()).hi("Java");
    }
}

commands:

$ javac hello/Hello.java
$ java hello/Hello
Java calling Java
$ scalac ScalaCallsJava.scala
$ scala ScalaCallsJava
Scala calling Java

Andere Tipps

Your scala code (as far as I can see from your question) is in the default package, so you need to import the Java class using its fully-qualified name (i.e. including the package as well as the classname)

import hello.Hello

Obviously you also need to ensure that:

  • All of the Scala and Java classes are getting compiled to classfiles
  • All of the Scala and Java classfiles are on the classpath

How you do this will depend on your environment. If you do this through an IDE like Eclipse then it should just work if you have a standard project structure.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top