开发者

String representation of objects as in Scala REPL

Is there a simple way to convert a Scala object to the string representation given in the REPL? For example, for Array(2, 3, 5), I'd like to get the string "Array(2, 3, 5)", and for Stream from 2, I'd like to get开发者_开发百科 "Stream(2, ?)".


The REPL uses the toString method to generate its string representations of values. Thus:

Array(1, 2, 3).toString      // => "Array(1, 2, 3)"

This works on all versions of Scala (2.7, 2.8, etc).


The more usual way is to use the mkString method of Array (same in 2.7 and 2.8):

scala> val a1 = Array(1, 2, 3)
a1: Array[Int] = Array(1, 2, 3)

scala> a1.mkString
res0: String = 123

scala> a1.mkString(", ")
res1: String = 1, 2, 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜