Can someone help me understand the problem often encountered when working with arrays?
The problem that arrays are sometimes mysteriously printed as
[Lscala.Tuple2;@724a1b65: Array[(String, Int)]
It’s a really curious thing when encountered by new students.
Is this only an artifact of old Scala versions? or is it evidence that the programmer’s approach is wrong?
The following use of mapValues works fine in 2.12. It is easy to understand, and concise.
val tale = Array("it", "was", "the", "best", "of", "times", "it", "was",
"the", "worst", "of", "times", "it", "was", "the", "age",
"of", "wisdom", "it", "was", "the", "age", "of", "foolishness",
"it", "was", "the", "epoch", "of", "belief", "it", "was", "the",
"epoch", "of", "incredulity", "it", "was", "the", "season", "of",
"light", "it", "was", "the", "season", "of", "darkness", "it",
"was", "the", "spring", "of", "hope", "it", "was", "the",
"winter", "of", "despair")
tale.groupBy(identity).mapValues(_.size)
But when trying the same thing in 2.13 we get a deprecation warning.
same in 2.13
When I try to take the advise of issued by the compiler then I get a MapView which is not computed.
tale.groupBy(identity).view.mapValues(_.size)
And to see the content I added .toArray and got [Lscala.Tuple2;@724a1b65: Array[(String, Int)]
with .toArray
What is the correct way to pretty print such an Lscala object?
BTW I also see that using .toMap
rather than .toArray
tale.groupBy(identity).view.mapValues(_.size).toMap
prints a much more reasonable result.
HashMap(belief -> 1, it -> 10, spring -> 1, was -> 10, hope -> 1, times -> 2, foolishness -> 1, light -> 1, of -> 10, the -> 10, worst -> 1, winter -> 1, epoch -> 2, best -> 1, darkness -> 1, despair -> 1, wisdom -> 1, incredulity -> 1, season -> 2, age -> 2): scala.collection.immutable.Map[String,Int]
12