Scala - printing arrays

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.


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

Try simply this:

  // create an array
  val array1 = Array(1,2,3)
  // print an array elements seperated by comma
  println(array1.mkString(","))
  // print an array elements seperated by a line
  println(array1.mkString("\n"))

  // create a function
  def printArray[k](a:Array[k])= println(a.mkString(","))
  printArray(array1)

Adding little more to Arjan's answer - you can use the mkString method to print and even specify the separator between elements. For instance :

val a = Array(1, 7, 2, 9)
a.mkString(" and ")
// "1 and 7 and 2 and 9"
a.mkString("<", ",", ">") //mkString(start: String, sep: String, end: String)
// "<1,7,2,9>" 

Tags:

Scala