18

In python REPL I can do things like:

>>> [1,2,3,4]
[1, 2, 3, 4]
>>> sum(_)
10

In clojure REPL I can do this:

user=> "Hello!"
"Hello!"

user=> *1
"Hello!"

Is there is something like this in Scala REPL?

Alex Miller
  • 69,183
  • 25
  • 122
  • 167
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228

3 Answers3

42

Yes, you can use dot notation to refer to the last result:

scala> List(1,2,3,4)
res0: List[Int] = List(1, 2, 3, 4)

scala> .sum
res1: Int = 10
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • This doesn't work for something like `scala> 4 + 5` and then `scala> . * 3`. Please provide more detail as my google search for 'scala .' is not helping. – Merlin Oct 09 '19 at 17:44
  • I should add it does work for something like a shell command result: `scala> :sh ls -l` and then `scala> .lines foreach println` – Merlin Dec 28 '19 at 17:20
8

You can refer to the previous output as resN for some N. You've probably noticed that in the Scala REPL, results are printed in the form resN: Type = value:

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> List(1,2,3,4)
res0: List[Int] = List(1, 2, 3, 4)

scala> "Hello!"
res1: java.lang.String = Hello!

Well, that resN is a real variable name. In this example, you can refer to the list as res0 and the string as res1 for (at least as far as I know) as long as the REPL is open:

scala> (res0.toString + res1) toLowerCase
res2: java.lang.String = list(1, 2, 3, 4)hello!
Antal Spector-Zabusky
  • 36,191
  • 7
  • 77
  • 140
-1

I normally just hit the key to bring back the last line of code and carry on typing. This has the advantage of keeping the whole expression together for easy cutting-and-pasting or editing later.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180