Scala - REPL



Introduction to Scala REPL

REPL stands for Read Evaluate Print Loop which is a command line tool. REPL is used for expression, evaluation and execution of small code snippets. Just like Java Shell, Scala REPL is great for beginners and people who want to try out new libraries or language features.

First, REPL reads the input given on the Scala command line. Then evaluates the given input and displays the result on the screen. It is ready to read the next input and process continues in loop. In the scope of current input, previous results are automatically imported as needed. REPL reads input expressions at the prompt during interactive mode. It then transforms these expressions into executable templates, compiles and executes result.

Implementation of REPL

  • You can use switch -Yrepl-class-based to wrap either object and class in user code.
  • Every input line is compiled individually.
  • Automatically generated imports include dependencies from previous lines.
  • You can control implicit import of scala.Predef by providing explicit import.

REPL Installation

Scala REPL is included with Scala when you install it. So, you can use it whenever you have Scala on your computer. You need to run "scala" command in your terminal then this is what will appear in our terminal:

Welcome to Scala 3.3.1 (21.0.1, Java Java HotSpot(TM) 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.

scala>

Useful Commands and Features of REPL

Running Scala in a terminal shell can be useful. REPL includes many useful commands and features. We have discussed some of them.

1. help Command

You need to hit `:help` command which will prints these list of available commands:

scala> :help
The REPL has several commands available:

:help                    print this summary
:load <path>             interpret lines in a file
:quit                    exit the interpreter
:type <expression>       evaluate the type of the given expression
:doc <expression>        print the documentation for the given expression
:imports                 show import history
:reset [options]         reset the repl to its initial state, forgetting all session entries
:settings <options>      update compiler options, if possible

scala>

2. load Commad

The `:load` command loads and runs code from a file in the REPL.

For example, if you have file names `script.scala` with following content:

case class Person(name: String, Roll:Int)
val me = Person("Mithlesh", 101)

You can run this file using `:load` command:

scala> :load script.scala
// defined case class Person
val me: Person = Person(Mithlesh,101)

scala> me
val res0: Person = Person(Mithlesh,101)

scala>

3. paste Command

One of the first obstacles we encounter when using a REPL is the fact that, by default, code is evaluated line by line. So, multi-line code like functions can not be executed without use of `paste` command. This command is used to paste and load code in the REPL. First type :paste in REPL then paste your block of code.

4. lastException Binding

IastException is bound for the last thrown exception. For example,

scala> throw new NullPointerException("Oops, a null reference!")
java.lang.NullPointerException: Oops, a null reference!
  ... 32 elided

scala> lastException
res4: Throwable = java.lang.NullPointerException: Oops, a null reference!

5. reset Command

If you want to clear variables or functions from our REPL session. You can use the ':reset' command. When you reset a session, you can not use the definitions from before anymore.

For example,

scala> val x = 42
x: Int = 42

scala> def bar(): String = "hello"
bar: ()String

scala> :reset
Resetting interpreter state.
Forgetting this session history:

val x = 42
def bar(): String = "hello"

Forgetting all expression results and named terms: x, bar

scala> x
<console>:12: error: not found: value x
       x
       ^

6. silent Command

System shows the definition when you create variable or function. You can disable it by using `silent` command.

For example,

scala> val x = 42
x: Int = 42

scala> :silent

scala> val y = "Hello, Scala!"

scala>

7. quit Command

To end a REPL session, you can use the ':quit' command or press ctrl-D.

Working with Dependencies of REPL

While Scala REPL is not designed for large projects, it can be useful by adding extra jars to the classpath.

1. require Commad

This command adds jars to classpath. For example,

scala> :require my-library-1.0.jar
Added '/path/to/my-library-1.0.jar' to classpath.

scala>

2. scala -cp

You can include jars when starting the REPL by using the '-cp' argument. For example,

scala -cp my-library-1.0.jar myScript.scala

3. sbt Console

An alternative method to bring in more dependencies in a REPL session is to utilize the 'sbt console' within an sbt project. When you use the 'sbt console' command, it starts a REPL with all the sbt dependencies included in the classpath.

Key Features of REPL

  • IMain Binding − The IMain of REPL is linked to $intp.
  • Tab Key for Completion − Use the tab key for auto-completion.
  • lastException Binding − lastException is tied to the last exception in the REPL.
  • :load Command − Use :load to load a file containing REPL input.
  • :javap Command − Utilize :javap to examine class artifacts.
  • -Yrepl-outdir Switch − Use -Yrepl-outdir to inspect class artifacts using external tools.
  • :power Command − Imports compiler components after entering compiler mode.
  • :help Command − Get a list of commands for user assistance.
Advertisements