The REPL: Answers in Seconds
You want to know what 1530 / 5 gives in Scala before you trust it in the logbook. Writing a file, adding a @main function and running it is slow for a one-line question. The REPL answers it in a second.
The rule
Type an expression, get its value and its type back.
REPL stands for read, evaluate, print, loop. Start it by running scala with no file, then type at the scala> prompt:
scala> 5.0 + 8.5
val res0: Double = 13.5Each answer has three parts:
res0is a name the REPL invents for the result, so you can use it again: typingres0 * 2next givesval res1: Double = 27.0.Doubleis the type the compiler inferred.13.5is the value.
Give things your own names and they stay available for the rest of the session. Continuing the same session:
scala> val runs = List(5.0, 8.5, 3.2, 10.0)
val runs: List[Double] = List(5.0, 8.5, 3.2, 10.0)
scala> runs.sum
val res2: Double = 26.7A few commands start with a colon and talk to the REPL itself rather than to Scala:
:type runs.maxprints just the type,Double.:resetforgets everything you defined.:helplists the commands, and:quitleaves.
Code that only prints returns Unit, and the REPL shows just the printed text: println("Logged") displays Logged with no res line.
If a line is unfinished, such as an if with no branches yet, the REPL waits for more lines before it evaluates anything.
The shortcut
Use the REPL as a question desk: one question per line, and read the type as well as the value. The type often answers a second question you did not know to ask.
Seconds per kilometre
1530 / 5.0returnsval res0: Double = 306.0. Her 5 km took 1530 seconds, so each kilometre took 306.
The REPL is for experiments. Anything the club will run again belongs in a .scala file, because a REPL session disappears when you quit.
Drills
Answer fast — trust the rule.
In a fresh REPL you type 5.0 + 8.5. What is shown?
Which input shows only the type of runs.max?
Right after val res0: Double = 13.5, you type res0 * 2. What comes back?
What does the REPL display for println("Logged")?
Which job is the REPL the wrong tool for?
Remember
- Run
scalawith no file to start the REPL; each result shows a name, a type and a value. - Shortcut: one question per line, and read the type too.
- Trap: leaving real work in a REPL session; move it into a file.
