How to enter multiline commands (statements) into the Scala REPL

When you want to test a multiline command/statement in the Scala REPL, you can easily run into a problem where the REPL gets confused, or more accurately, it attempts to evaluate your statement too early.

As a simple example of this, imagine that you want to test the Scala if statement syntax. You begin typing your if statement normally, but when you hit [Enter] after your second line, you’ll see that everything blows up:

scala> if (true) 
     |   print "t"
<console>:2: error: ';' expected but string literal found.
         print "t"
               ^

This error happens because the Scala REPL environment isn’t exactly the same as working in something like an IDE. The REPL generally just sees one line of code at a time, attempts to interpret it, and print the result of that line. If your statement doesn’t end on one line, boom!

Resolving the problem with the :paste command

A simple way to get around this multiline statement problem is to use the :paste command in the REPL. Before entering your multiline statement, type the :paste command into the REPL:

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

When you do this, the REPL prompts you to paste in your command — your multiline expression — and then press [Ctrl][D] at the end of your command. In this example I paste in my complete multiline if statement, and then press [Ctrl][D]:

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

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

// Exiting paste mode, now interpreting.

that was true

After entering my four-line if statement, I pressed [Ctrl][D], and after that the line “// Exiting paste mode, now interpreting” was printed, followed by the output from my if statement (“that was true”).

Entering multiline commands in the REPL without :paste

In some cases you can create multiline commands in the Scala REPL without using the :paste command. For the example shown, you just need to add curly braces to the if statement to let the REPL know that a block is coming up:

scala> if (true) {
     |   print("true")
     | } else {
     |   print("false")
     | }
true

However, you can’t always do this, and I usually prefer to type :paste and then enter my statements just like I would in an IDE.

In summary, I hope this example of how to use the :paste command to let you enter multiline commands in the Scala REPL has been helpful.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.