NullPointerException when using IMain.bind()

I am trying to use the Scala interpreter (IMain) to bind an object to a variable. I am using Scala 2.13.6.

I create an IMain using:

private def initInterpreter: IMain = {
    val settings = new GenericRunnerSettings(println _)
    settings.usejavacp.value = true
    val flusher = new java.io.PrintWriter(System.out)
    val replReporter = new ReplReporterImpl(settings, flusher)
    new IMain(settings, replReporter)
}

Then, I try to call bind() using:

interpreter = initInterpreter
var sample = 50
interpreter.bind("sample", "Int", sample)

When I do this, I get a NullPointerException:

java.lang.NullPointerException: null
        at scala.tools.nsc.CompilationUnits$CompilationUnit.<init>(CompilationUnits.scala:44)
        at scala.tools.nsc.CompilationUnits$CompilationUnit.<init>(CompilationUnits.scala:45)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.compile(IMain.scala:735)
        at scala.tools.nsc.interpreter.IMain.bind(IMain.scala:554)
        ...

I looked at the ReadEvalPrint and CompilationUnit source codes to try to see where the null is coming from, but it’s not clear to me.

https://github.com/scala/scala/blob/v2.13.6/src/compiler/scala/tools/nsc/CompilationUnits.scala#L45

https://github.com/scala/scala/blob/v2.13.6/src/repl/scala/tools/nsc/interpreter/IMain.scala#L549

Also, pardon the simple example – I am trying to get it to work for an Int before I use it for my own self-defined type.

Any suggestions?

➜  ~ scala -nobootcp
Welcome to Scala 2.13.6 (OpenJDK 64-Bit Server VM, Java 15).
Type in expressions for evaluation. Or try :help.

scala> val sc = scala.tools.nsc.interpreter.shell.Scripted()
val sc: scala.tools.nsc.interpreter.shell.Scripted = scala.tools.nsc.interpreter.shell.Scripted@78c23ade

scala> sc.intp.bind("foo", "String", "hello, world")
val res0: tools.nsc.interpreter.Results.Result = Success

scala> sc.intp.interpret("foo")
val res1: tools.nsc.interpreter.Results.Result = Success

scala> sc.intp.interpret("println(foo)")
hello, world
val res2: tools.nsc.interpreter.Results.Result = Success