Scala REPL unable to import packge

2019-05-15 13:41发布

问题:

I'm trying to import com.lambdaworks.crypto.SCryptUtil (from crypto) in the Scala REPL. I'm running the REPL from the Java directory containing com/lambdaworks/crypto.

The REPL can't find com.lambdaworks.crypto.SCryptUtil, but it can autocomplete up to com.lambdaworks.crypto but can't find anything after that.

When I used the REPL in the IntelliJ IDEA after including the package in my project, I was able to find the SCryptUtil class.

Am I missing some classpath parameters that are required for import?

回答1:

The REPL won't compile the Java code for you—it's only autocompleting that far because it's aware of the directory structure, but once it gets to the crypto directory it won't find any class files.

You can see this more dramatically by moving up a directory and opening a new REPL—you'll be able to autocomplete import java.com.lambdaworks.crypto, even though that's obviously not a real package hierarchy.

In this case you can move to the project root, run mvn compile to compile the Java code, and then start the REPL like this (still in the project root):

scala -classpath target/classes

Now you can import com.lambdaworks.crypto.SCryptUtil.

This only works because the project doesn't have any runtime dependencies, though—in other cases you may need either to add other things to the classpath, to build a JAR with the dependencies baked in (e.g. with the Maven Assembly plugin), or to use the mvn scala:console goal of the Maven Scala plugin.