0

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.

2
  • 4
    don't you need to put "import hello.Hello" because it is in the hello package? Commented Apr 17, 2014 at 5:51
  • 1
    Are You sure that java Hello class is compiled to class file? Commented Apr 17, 2014 at 6:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i do this through the command line. like i said, i had already tried this.
i got it to work by compiling scala. is there no way to write this as a scala script (i.e. no main class)? thanks!
0

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

Comments

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.