如何让Scala REPL在字符串项周围显示带引号的List [String]?
例如,如果我定义
scala> val colorPairs = List("red, green", "yellow, blue")
colorPairs: List[String] = List(red, green, yellow, blue)
显示的是没有引号的字符串,使其看起来好像 上面有4个字符串项而不是2.我该如何解决这个问题?
答案 0 :(得分:3)
不确定它是否可以在scala REPL中配置,但您可以尝试Ammonite。
@ val colorPairs = List("red, green", "yellow, blue")
colorPairs: List[String] = List("red, green", "yellow, blue")
答案 1 :(得分:2)
toString
的{{1}}方法生成没有引号的表示:
List
这是在TraversableLike:
中实施的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)
(感谢som-snytt更新)但是,ScalaRunTime提供了各种特殊情况渲染,例如:
/** 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 + "(", ", ", ")")
由于以下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 ")
s:
case
当然,有多种方法可以更准确地显示列表内容:
case "" => "\"\""
case x:String => if (x.head.isWhitespace || x.last.isWhitespace) "\"" + x + "\"" else x
或者您可以使用新方法丰富List和类似的集合:
scala> colorPairs foreach println
red, green
yellow, blue
scala> colorPairs.map("\"" + _ + "\"")
res2: List[String] = List("red, green", "yellow, blue")