FLINTERS Engineer's Blog

FLINTERSのエンジニアによる技術ブログ

ScalaのREPLには2通りの方法がある

こんにちは、池田です。

Scalaを学習する際や関数の挙動、動作を確認したいときに、REPLを活用しているかと思いますが

上のようにREPLでimportできないライブラリを使えるようにしたい時にどうするればいいのか?

ご存知でしょうか?

僕はこのようにREPLでimportできないライブラリ(libraryDependenciesが必要なライブラリ)を使う方法を知らず 不自由な思いをしていたので紹介します。



1.REPLを使う2つの方法

まずREPLを使うときに2つの方法があります。

scalaコマンド を使う方法とsbt consoleを使う方法です。

Ammonite REPLという通常のREPLよりもより豊かなシェル環境を提供する代替REPLもありますがここでは通常のScalaのREPLを紹介します。

scalaコマンドの場合

$ scala
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions to have them evaluated.
Type :help for more information.

scala> 

▼ sbt consoleの場合

$ sbt console
[info] Loading global plugins from /Users/taketoikeda/.sbt/0.13/plugins
[info] Set current project to testProject (in build file:/Users/taketora/test_sbt/)
[info] Starting scala interpreter...
[info] 
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions for evaluation. Or try :help.

scala> 

どちらも対話型でscalaのコマンドが使える環境になるのですが、それぞれ使いやすいケースが異なります。

2. Scalaコマンドについて

Scalaコマンドは、Scalascala.tools.nsc.interpreterのパッケージがREPLに相当し*1Scalaダウンロードすることで使えるようになります。

3. sbt consoleについて

一方sbt consoleは、sbt(simple build tool)のconsoleコマンドを使ってREPLができるようになります。 sbtとはビルドツールで、sbtをインストールすることで使えるようになります。

ドキュメント(sbt Reference Manual — 実行)のsbt consoleの説明には

コンパイル済のソースと依存ライブラリにクラスパスを通して、Scala インタプリタを開始する。

と記載されており、すでにbuild.sbtなどで設定したsbtでプロジェクトがある場合は、sbt console を使うと依存ライブラリにクラスパスを通して importできるようにしてくれます。

4.それぞれのユースケース

Scalaコマンドsbt console
実行環境にScalaがインストールされているsbtでビルドしているプロジェクトがある
数行のスニペットを実行したいプロジェクトで定義しているクラスをREPLで使いたい
ScalaJavaパッケージにあるライブラリだけを使うlibraryDependenciesが必要なライブラリを使う
任意のScalaのバージョンで実行したい

Scalaコマンドは、 Scalaパッケージにあるライブラリだけ使う場合に向いており、

sbt consoleはlibraryDependenciesが必要なライブラリを使いたい時プロジェクトで定義しているクラスをREPLで使いたい時に向いています。

そのため冒頭にあったREPLでlibraryDependenciesが必要なライブラリを試したい時は、sbt consoleを使うといいです。

$ sbt
[info] Loading global plugins from /Users/t_ikeda/.sbt/0.13/plugins
[info] Set current project to sbt (in build file:/Users/t_ikeda/sbt/)
> set libraryDependencies += "joda-time" % "joda-time" % "2.9.9"
[info] Defining *:libraryDependencies
[info] The new value will be used by *:allDependencies, *:dependencyPositions
[info] Reapplying settings...
[info] Set current project to sbt (in build file:/Users/t_ikeda/sbt/)
> console
[info] Updating {file:/Users/t_ikeda/sbt/}sbt...
[info] Resolving jline#jline;2.14.3 ...
[info] Done updating.
[info] Starting scala interpreter...
[info] 
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_91).
Type in expressions for evaluation. Or try :help.

scala> import org.joda.time.DateTime
import org.joda.time.DateTime

scala> val daye = new DateTime(2017,7,11,12,0,0)
daye: org.joda.time.DateTime = 2017-07-11T12:00:00.000+09:00

scala> 

※build.sbtに書くlibraryDependenciesは、sbtの場合setコマンドを使うことで一時的に設定できます。

REPLはScalaを学ぶ時に触れる機能だと思いますが、Scalaパッケージ以外のライブラリもどんどん触れて Scalaを学んで行きましょう。

参考ブログ