Home > Blockchain >  Unable to run compiled scala project wither with scala or java "classNotFoundException: scala.x
Unable to run compiled scala project wither with scala or java "classNotFoundException: scala.x

Time:12-19

I created a project with sbt new scala/scala3.g8

This is my modified build.sbt

val scala3Version = "3.2.1"

lazy val root = project
.in(file("."))
.settings(
  name := "bloomberg-clone",
  version := "0.1.0-SNAPSHOT",

  scalaVersion := scala3Version,

  libraryDependencies  = "org.scala-lang.modules" %% "scala-xml" % "2.1.0"
)

I've scala 3.2.1 and java 17 installed in my machine. My project structure is the following

bloomberg-clone % ls
README.md       build.sbt       project         src             target

src / main / scala / Main.scala

Main.scala has the following imports and @main method:

import scala.io.Source
import java.io.*
import scala.xml.{Elem, Node, Text, XML}
import scala.xml.transform.{RewriteRule, RuleTransformer}

@main def Main(inputFilePath: String, outputFilePath: String, numCopies: Int): Unit = 
{
val xmlList = loadXml(inputFilePath)
xmlList.flatMap { (node,fileName) =>
for (i <- 1 to numCopies) yield {
  val modifiedNode = transformXml(node)
  val modifiedOutputFilePath = createModifiedOutputFilePath(fileName,outputFilePath, i)
  writeXml(modifiedNode, modifiedOutputFilePath)
}
}
}

When I run the code from IntellJ, it works. When I compile using sbt compile and sbt package, and run the resulting jar as scala out.jar a b 3 I get an error java.lang.ClassNotFoundException: scala.xml.XML$. If I run it with java -jar out.jar a b 3, I get Error: Unable to initialize main class Main Caused by: java.lang.NoClassDefFoundError: scala/util/CommandLineParser$ParseError.

Why is scala-xml not being packaged ?

CodePudding user response:

As mentioned by Luis Miguel Mejía Suárez in the comments, the jar doesn't contain the scala-xml classes. Assing sbt-assembly (project/plugins.sbt, create the file if it doesn't exist yet) addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.0")

And modifying the build.sbt

lazy val app = (project in file("."))
.settings(
assembly / mainClass := Some("Main"),
// other settings
)

When running sbt assembly the jar under target/scala-3.2.1/ contains all the dependencies (size is 7,9MB I guess this needs to be taken into account for larger applications)

  • Related