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)("that was true")else("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:
Type the
:pastecommand in the REPL.Paste in your block of code (Command-V on a Mac, Ctrl-V on Windows).
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:
caseclassPerson(name:String)
You can load that source code into the REPL environment like ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access