Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - printing arrays

Tags:

scala

It seems like the support for printing arrays is somewhat lacking in Scala. If you print one, you get the default garbage you'd get in Java:

scala> val array = Array.fill(2,2)(0)              array: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))  scala> println(array) [[I@d2f01d 

Furthermore, you cannot use the Java toString/deepToString methods from the java.util.Arrays class: (or at least I cannot figure it out)

scala> println(java.util.Arrays.deepToString(array)) <console>:7: error: type mismatch;  found   : Array[Array[Int]]  required: Array[java.lang.Object]        println(java.util.Arrays.deepToString(array)) 

The best solution I could find for printing a 2D array is to do the following:

scala> println(array.map(_.mkString(" ")).mkString("\n")) 0 0 0 0 

Is there a more idiomatic way of doing this?

like image 543
I82Much Avatar asked Jul 25 '10 05:07

I82Much


People also ask

Does Scala have Arrays?

Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

How do you create an array of objects in Scala?

Creating an Array and Accessing Its ElementsScala translates the first line in the example above into a call to Array::apply(), defined in the Array companion object. Such a method takes a variable number of values as input and creates an instance of Array[T], where T is the type of the elements.


2 Answers

In Scala 2.8, you can use the deep method defined on Array, that returns an IndexedSeq cointaining all of the (possibly nested) elements of this array, and call mkString on that:

 scala> val array = Array.fill(2,2)(0) array: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))  scala> println(array.deep.mkString("\n")) Array(0, 0) Array(0, 0) 

The IndexedSeq returned does have a stringprefix 'Array' by default, so I'm not sure whether this gives precisely what you wanted.

like image 140
Arjan Blokzijl Avatar answered Oct 06 '22 04:10

Arjan Blokzijl


How about this:

scala> val array = Array.fill(2,2)(0) array: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))  scala> import scala.runtime.ScalaRunTime._ import scala.runtime.ScalaRunTime._  scala> val str = stringOf(array) str: String = Array(Array(0, 0), Array(0, 0)) 
like image 39
Eastsun Avatar answered Oct 06 '22 04:10

Eastsun