String representation of objects, as in Scala REPL

Is there an easy way to convert a Scala object to the string representation specified in the REPL? For example, for Array(2, 3, 5)I would like to receive a line "Array(2, 3, 5)", and for Stream from 2I would like to receive "Stream(2, ?)".

+3
source share
2 answers

REPL uses a method toStringto generate its string representations of values. Thus:

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

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

+4
source

A more common way is to use the mkString method of the array (the 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
+2
source

Source: https://habr.com/ru/post/1726775/


All Articles