Why ClassNotFoundException from sbt console but not Scala REPL

Viewed 39

First I delete the .sbt from my home-directory, then I make an empty project directory, and in that directory I create a build.sbt file:

echo 'ThisBuild / scalaVersion := "3.1.3"' > build.sbt

Then I run sbt console and at the console prompt attempt the following Class.forname() invocation, which produces the following ClassNotFoundException:

[info] welcome to sbt 1.7.1 (Debian Java 11.0.16)
Welcome to Scala 3.1.3 (11.0.16, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                    
scala> Class.forName("java.sql.Connection")
java.lang.ClassNotFoundException: java.sql.Connection
  at dotty.tools.repl.AbstractFileClassLoader.findClass$$anonfun$1(AbstractFileClassLoader.scala:46

On the other hand, if I start the REPL with the plain-old scala command, then invoke the same forName() I see this:

Welcome to Scala 3.1.3 (11.0.16, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                                                            
scala> Class.forName("java.sql.Connection")
val res0: Class[?] = interface java.sql.Connection

So the same forName() invocation elicits different behavior in the sbt console versus the Scala REPL: a ClassNotFoundException in the former versus returning an instance of the Class class in the latter.

The sbt console also produces that ClassNotFoundException with any of the following lines in the build.sbt file:

classLoaderLayeringStrategy := ClassLoaderLayeringStrategy.AllLibraryJars

or

classLoaderLayeringStrategy := ClassLoaderLayeringStrategy.ScalaLibrary

or even

classLoaderLayeringStrategy := ClassLoaderLayeringStrategy.Flat

What is it about sbt that causes the exception, and how can sbt be made to succeed?

0 Answers
Related