Multiline Statements in the Scala REPL

Scala Snippet: multiline statements in the REPL console

One of the coolest things a standard Scala install will give you, is the Scala interpreter.
Technically speaking, this is not an interpreter. In the background, each statement is quickly compiled into bytecode and executed on the jvm.
Therefore, most people refer to it as the REPL: Read-Evaluate-Print-Loop.

You can access it by starting a command shell on your system and typing in ‘scala‘.
Do make sure your either run it from the place where scala is installed or have scala on your environment PATH.

By using the repl, you can quickly experiment and test out different statements. Once you press ENTER it will evaluate the statement and display the result.

Frequently you want to execute multi-line statements and luckily the repl has a solution for that.

Simply type in :paste and the repl will accept multiline statements.
To exit this mode and evaluate your code, simply type CTRL+D.

Example:

$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) Client VM, Java 1.7.0_75).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Camera {
//this is a multiline example in the REPL
val brand:String = "Canon"
val model:String = "5D mark III"
}
// Exiting paste mode, now interpreting.
defined class Camera
scala> val cam = new Camera
cam: Camera = Camera@bfd117
scala> cam.brand
res0: String = Canon

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *