Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

Scala - printing arrays

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("
"))
0 0
0 0

Is there a more idiomatic way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...