IntelliJ Community Edition 2016 Scala Worksheet shows strange output instead of literal value

204 Views Asked by At

I've used the scala worksheet in InteliJ and have run across a problem where the right-hand side (REPL-like output) shows what appears to be a namespace or memory address instead of the useful-to-a-human literal value.

In the scala REPL (not IntelliJ) the following is quite sane

scala> val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

However, in the Scala worksheet the same yields a not-so-useful output

nums: Array[Int] = [I@1a2a52bf

After some light googling and reading I tried the following

val nums = new Array[Int](10)
nums
nums.toString()
nums.mkString(", ")

Which output

nums: Array[Int] = [I@1a2a52bf
res0: Array[Int] = [I@1a2a52bf
res1: String = [I@1a2a52bf
res2: String = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

There's got to be a simple solution or explanation for this that I'm missing. Has anyone run across this and fixed it before?

Here's a worksheet screenshot for reference:

screenshot

1

There are 1 best solutions below

0
On BEST ANSWER

IntelliJ's worksheet uses toString to print variable. Array[Int] in Scala corresponds to Java's int[] which doesn't override Object's toString method.

Here is Object's toString method:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Scala's REPL on the other hand has special logic for certain classes, Array among them.

There is nothing to "fix", it's just how these tools are designed. If you want to pretty print Array's value in Idea's worksheet, use java.util.Arrays.toString or convert value to another collection:

val a = Array(1,2,3)
a.toString
java.util.Arrays.toString(a)
a.toSeq

Produces:

a: Array[Int] = [I@4df3d702
res0: String = [I@4df3d702
res1: String = [1, 2, 3]
res2: Seq[Int] = WrappedArray(1, 2, 3)