tags:

views:

131

answers:

2

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, ?)".

+1  A: 

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
Randall Schulz
+1  A: 

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).

Daniel Spiewak
Ah, I was assuming that `println` would use `toString`, but apparently on scala.Array, it doesn't.
Mitchell Koch
Unfortunately, there's a lot of magic going on surround both `Array` and `toString`. The `println` method just delegates to `System.out.println` (on the JVM) and so the result is whatever the *Java* implementation of `toString` is for that particular object. Scala intercepts `toString` when it knows something is an `Array`, but it can't do that when the method call in question is inside Java code.
Daniel Spiewak