有时,我们需要在scala交互模式(REPL: read–eval–print loop)下试验第三方的jar包。而直接用scala命令进入的REPL只能使用默认的scala和java标准库。这时可以用sbt console的方式进入REPL模式。而关键点在于,你需要在运行sbt console的目录下定义build.sbt文件---就和工程项目中的build.sbt文件一样的。
例如,定义build.sbt为:
scalaVersion := "2.12.8"
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-json" % "2.7.3"
)
假设后面我们的工作目录,也就是文件build.sbt的目录是/REPLwJars,运行sbt console:
➜ REPLwJars sbt console
[info] Loading global plugins from /Users/xxxx/.sbt/0.13/plugins
[info] Loading project definition from /Users/xxxx/MyProjs/Projs_Scala/REPLwJars/project
[info] Set current project to replwjars (in build file:/Users/xxxx/MyProjs/Projs_Scala/REPLwJars/)
[info] Starting scala interpreter...
[info]
Welcome to Scala 2.12.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181).
Type in expressions for evaluation. Or try :help.
scala> import play.api.libs.json._
import play.api.libs.json._
这样,就可以在REPL中使用第三方jar包了。
如果将scala版本从2.12.x换成2.11.y:
scalaVersion := "2.11.12"
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-json" % "2.7.3"
)
则会出现这个样的错误:
➜ REPLwJars sbt console
[info] Loading global plugins from /Users/xxxx/.sbt/0.13/plugins
[info] Loading project definition from /Users/xxxx/MyProjs/Projs_Scala/REPLwJars/project
[info] Set current project to replwjars (in build file:/Users/xxxx/MyProjs/Projs_Scala/REPLwJars/)
[info] Starting scala interpreter...
[info]
Welcome to Scala 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181).
Type in expressions for evaluation. Or try :help.
[ERROR] Failed to construct terminal; falling back to unsupported
java.lang.NumberFormatException: For input string: "0x100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
......
这时你就需要先更新一下环境变量TERM的值:
➜ REPLwJars export TERM=xterm-color
再运行sbt console就不会有错误了。