在scala交互模式下使用第三方jar包

本文介绍了如何在Scala交互模式(REPL)下使用第三方jar包。通过创建`build.sbt`文件并使用`sbt console`命令,可以在REPL环境中引入所需库。当遇到scala版本不兼容问题时,调整环境变量TERM的值可以解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时,我们需要在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就不会有错误了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值