14.2. Pasting and Loading Blocks of Code into the REPL

Problem

You want to experiment with some code in the Scala REPL, and typing it in or trying to paste it into the REPL won’t work.

Solution

The REPL is “greedy” and consumes the first full statement you type in, so attempting to paste blocks of code into it can fail. To solve the problem, either use the :paste command to paste blocks of code into the REPL, or use the :load command to load the code from a file into the REPL.

The :paste command

Attempting to paste the following if/else block into the REPL will cause an error:

if (true)
  print("that was true")
else
  print("that was false")

But by issuing the :paste command before pasting in the code, the code will be interpreted properly:

scala> :paste
// Entering paste mode (ctrl-D to finish)

if (true)
  print("that was true")
else
  print("false")

[Ctrl-D]

// Exiting paste mode, now interpreting.
that was true

As shown, follow these steps to paste your code into the REPL:

  1. Type the :paste command in the REPL.

  2. Paste in your block of code (Command-V on a Mac, Ctrl-V on Windows).

  3. Press Ctrl-D, and the REPL will evaluate what you pasted in.

The :load command

Similarly, if you have source code in a file that you want to read into the REPL environment, you can use the :load command. For example, assume you have the following source code in a file named Person.scala in the same directory where you started the REPL:

case class Person(name: String)

You can load that source code into the REPL environment like ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.