In this tutorial, we’ll learn different approaches to printing the contents of an Array in Scala.
2. Arrays in Scala
If we try to print the contents of an Array in scala we’ll have a surprise:
scala> val a = Array(1,2,3) val a: Array[Int] = Array(1, 2, 3) scala> println(a) [[email protected]
We see that something weird was printed instead of the actual contents. But If we try to just use the println method with Lists, Sets, or Maps, everything just works as expected:
scala> val l = List(1,2,3) println(val l: List[Int] = List(1, 2, 3) scala> println(l) List(1, 2, 3) scala> val s = Set(1,2,3) val s: Set[Int] = Set(1, 2, 3) scala> println(s) Set(1, 2, 3) scala> val m = Map(1 -> "a", 2 -> "b", 3 -> "c") val m: Map[Int, String] = Map(1 -> a, 2 -> b, 3 -> c) scala> println(m) Map(1 -> a, 2 -> b, 3 -> c)
So what happens with Arrays and why doesn’t it print the contents nicely as with other collections?
While List, Set, and Map are actual Scala collections, the Array type is just the Scala equivalent of Java native arrays (e.g., String to represent a native array of Strings). So when we try to print the array contents, we just get whatever is defined in the Array.toString method (usually is the object hashcode, but it depends on the platform).
Let’s go through some workarounds.
3. Using Loops
The most naive solution is to just iterate through the array elements and print each of them:
scala> val a = Array(1,2,3) val a: Array[Int] = Array(1, 2, 3) scala> a.foreach(println) 1 2 3
If we don’t want to print each element in a different line, we can use the print or printf methods instead.
4. Using mkString
Another handy method we can make use of is the mkString method which exists in almost all scala collections-like objects:
scala> a.mkString val res1: String = 123
The mkString method also accepts a custom separator if we want to modify the output:
scala> a.mkString(",") val res2: String = 1,2,3 scala> a.mkString(", ") val res3: String = 1, 2, 3
5. Converting to Scala Collections
While it may not be a very performant solution, we can also just convert our Array into a scala collection which would print nicely. The List is the most equivalent collection:
scala> val l = a.toList val l: List[Int] = List(1, 2, 3) scala> println(l) List(1, 2, 3)
6. Using ScalaRunTime.replStringOf
There’s another solution that most developers are not familiar with. We can use the ScalaRunTime object:
scala> runtime.ScalaRunTime.replStringOf(a, a.length) val res5: String = "Array(1, 2, 3) "
In this article, we investigated why printing the contents of an Array is not as obvious as it seems and several solutions for that.