Dheeraj Kumar

Ruby, Golang, Scala, Javascript

Paste Mode in Scala REPL

| Comments

Scala has a great REPL, which is extremely useful especially for a beginner like me. Coming from the Ruby land and the browser consoles, I found it familiar, like a friendly face in a different country.

I had issues while trying to execute multiline code in the REPL. I did try writing them in the same line, but it gets unwieldy very quickly. Upon googling, I discovered via a very useful blog post, that it has a paste mode that solves this exact problem.

So now, all I have to do is to type :paste, followed by my code, and terminate the mode with a Ctrl+D.

However, that’s not all it does! I can even evaluate the contents of a file:

1
2
3
scala> :paste hello.scala
Pasting file hello.scala...
defined object Hi

I could use :load instead, but it has a limitation. Quoting the changelog:

:load can only interpret a file from top to bottom which is for example a problem when there is a reference to a definition that is defined later. :paste is overworked to solve this limitation. It now can not only load a file but also handle it as a single unit.

I can also ask the REPL to consider my input as a scala file, instead of a script. This is activated by using the -raw parameter. The example from the changelog explains it succintly:

1
2
3
4
5
6
7
8
9
10
11
scala> :paste -raw
// Entering paste mode (ctrl-D to finish)

package abc
case class Foo(bar: Int)

// Exiting paste mode, now interpreting.


scala> abc.Foo(5)
res5: abc.Foo = Foo(5)

Note that if I don’t use the parameter, this happens:

1
2
3
4
5
6
7
8
9
10
11
scala> :paste
// Entering paste mode (ctrl-D to finish)

package abc
case class Foo(bar: Int)

// Exiting paste mode, now interpreting.

<console>:1: error: illegal start of definition
       package abc
       ^

Comments