Scala REPL in Gradle

2020-02-28 03:14发布

问题:

At the moment Gradle's scala integration does not offer REPL functionality. How to ergonomically run a Scala REPL from Gradle with the appropriate classpath?

回答1:

Minimal build.gradle:

apply plugin: 'scala'

repositories{
  mavenCentral()
}

dependencies{
  compile "org.scala-lang:scala-library:2.11.7"
  compile "org.scala-lang:scala-compiler:2.11.7"
}

task repl(type:JavaExec) {
  main = "scala.tools.nsc.MainGenericRunner"
  classpath = sourceSets.main.runtimeClasspath
  standardInput System.in
  args '-usejavacp'
}

Credit to this answer for explaining how to direct stdin with standardInput and have REPL use the right classpath with args.

Notice the scala-compiler library is a dependency. That's where scala.tools.nsc.MainGenericRunner is found.

From the console a number of options are needed to run the REPL:

  • --no-daemon, if you are using a Gradle daemon. At the moment, the REPL does not respond to keystrokes if run from the daemon.

  • --console plain. A popular, but inferior alternative is --quiet. If run without one of these options, REPL's prompt is contaminated by Gradle's progress report. --console plain has the advantage that it also adjusts readline's behaviour so that rlwrap is unnecessary.

Full command to run the REPL is gradle repl --console plain --no-daemon, so creating an alias in your shell makes sense.