1

How do I get the Scala REPL to display a List[String] with quotes around the string items ?

For example, if I define

scala>  val colorPairs = List("red, green", "yellow, blue")
colorPairs: List[String] = List(red, green, yellow, blue)

What gets shown are the strings without quotes, making it appear as though there are 4 string items above instead of 2. How can I remedy this ?

femibyte
  • 3,317
  • 7
  • 34
  • 59

2 Answers2

3

Not sure if that's configurable in the scala REPL, but you could try Ammonite.

@ val colorPairs = List("red, green", "yellow, blue")
colorPairs: List[String] = List("red, green", "yellow, blue")
ed.
  • 2,696
  • 3
  • 22
  • 25
2

The toString method of List produces the representation without quotes:

scala> val colorPairs = List("red, green", "yellow, blue")
colorPairs: List[String] = List(red, green, yellow, blue)

scala> colorPairs.toString
res0: String = List(red, green, yellow, blue)

This is implemented in TraversableLike:

  /** Converts this $coll to a string.
   *
   *  @return   a string representation of this collection. By default this
   *            string consists of the `stringPrefix` of this $coll, followed
   *            by all elements separated by commas and enclosed in parentheses.
   */
  override def toString = mkString(stringPrefix + "(", ", ", ")")

(Update thanks to som-snytt) However, ScalaRunTime provides various special case rendering, for example:

scala> List("")
res3: List[java.lang.String] = List("")

scala> List("1")
res4: List[java.lang.String] = List(1)

scala> List(" 1 ")
res6: List[java.lang.String] = List(" 1 ")

which is due to the following cases:

case ""       => "\"\""
case x:String => if (x.head.isWhitespace || x.last.isWhitespace) "\"" + x + "\"" else x

There are various ways of showing the list contents more accurately, of course:

scala> colorPairs foreach println
red, green
yellow, blue

scala> colorPairs.map("\"" + _ + "\"")
res2: List[String] = List("red, green", "yellow, blue")

Or you could enrich List and similar collections with a new method for this:

implicit class TLWrapper(t: TraversableLike[String,_]){
     def show = t.mkString(t.stringPrefix + "(\"", "\", \"", "\")")
}

scala> List("red, green","yellow, blue").show
res10: String = List("red, green", "yellow, blue")
DNA
  • 42,007
  • 12
  • 107
  • 146
  • This works, but only for the specific case of List[String] (and not in the REPL). – Andy Hayden May 26 '16 at 21:44
  • It also works for any other `TraversableLike` (such as `Vector` or `Set`) but I agree it's not very convenient for the REPL. – DNA May 26 '16 at 22:04
  • 1
    This is mostly true, but it was a conscious design decision at some point. Consider `List(" a ")`, where quotes are injected to show the padding. It's the work of `scala.runtime.ScalaRunTime.stringOf`. – som-snytt May 26 '16 at 23:56
  • @som-snytt Thanks! - Have updated answer to take ScalaRunTime into account – DNA May 27 '16 at 09:24