0

after packaging and executing a Scala application (build.sbt with version 2.12.0, but in fact having 2.13.3 installed) with SBT (version 1.3.13), I get the following error:

Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.wrapRefArray([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray;
    at org.example.GreetWorld$.printMessage(GreetWorld.scala:5)

The source file GreetWorld.scala that caused the error looks like this:

package org.example

object GreetWorld {
      def printMessage(theMessage:String):Unit = {
            println(s"${theMessage} from me")
      }
}

The main file that is invoking the file above looks like this:

package org.example

object HelloWorld {
    def main(args: Array[String]) = {
        GreetWorld.printMessage("Hello")
    }
}

Does anybody know the root cause? At first I thought it has to do with the SBT shell picking Java 11, but even after changing my Windows' JAVA_HOME to Java 8, I still get the same error. Compiling and running it in SBT Shell works fine. Only the JAR execution fails.

Fortun
  • 37
  • 9

1 Answers1

1

The error is pretty simple. When you run package you create a JAR which only contains the classes corresponding to your source code, nothing more. And your code depends on the Scala stdlib, so if you try to run it with java - jar it will fail with a class path error.

You have 4 solutions:

  1. Run the JAR using scala directly. However, you need to use the same major version it was used to compile.

  2. Put the Scala library jar in the classpath when running. This is basically the same as above. Thus again, you have to use the same major version.

  3. Create an uber jar that already has the Scala stdlib (as well as any other dependency) in it, using sbt-assembly.

  4. Create a native distributable that will set up everything for you, using sbt-native-packager.

For local development and testing option 1 is usually the best one.
For simple projects option 3 is, IMHO, the simplest alternative.
And for very complex projects option 4 is very popular.

  • Ok I see. Number 1 it is. Actually I did run the jar using the scala shell, but it tries to run it with scala 2.13. I will check that and report back. – Fortun Aug 16 '20 at 14:47
  • So after defining the same scala version in build.sbt as the one I have installed on my laptop, the jar execution worked. Thank you! – Fortun Aug 17 '20 at 06:46