Ming Ming - 15 days ago 5
Scala Question

Scala Worksheet Intellij not evaluating results properly

I am running this scala code in IntelliJ Worksheet.

object sheet3 {
println("Welcome to new worksheet")
val nums = new Array[Int](10)
for (i <- 0 until nums.length) nums(i) = i * i
nums
val a = Array("Hello", "Friend")

a(0) = "Goodbye"
println(a)

for (i <- 0.until(a.length)) print(i)

}


However, I am getting this result
Results

I was hoping for this instead when I run in scala repl

scala> val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)


Thanks for the help

Additional Problem

object reply extends App{
println("Welcome world")
val words = Array("Marry", "had", "a", "little", "lamb", "its", "fleece",
"was", "white", "as", "snow")
println(words.groupBy(_.substring(0, 1)))
println(words.mkString(" "))
}


Results below

Welcome world
s -> [Ljava.lang.String;@32e6e9c3 f -> [Ljava.lang.String;@2669b199 a -> [Ljava.lang.String;@2344fc66 M -> [Ljava.lang.String;@458ad742 i -> [Ljava.lang.String;@5afa04c l -> [Ljava.lang.String;@6ea12c19 h -> [Ljava.lang.String;@6a024a67 w -> [Ljava.lang.String;@7921b0a2
Marry had a little lamb its fleece was white as snow

Process finished with exit code 0


In code above, how can I get the results to print Strings instead of java.lang.String;@32e6e9c3.
Was unsuccessful when tried with
println(words.groupBy(_.substring(0, 1)).mkString)

Answer

The answer to your 2nd question is much like the answer to the 1st. The problem is that you're using Array which implements the ugly Java toString. If you used a Scala collection like Seq, Vector, or List, you'd see a cleaner output.

Since the groupBy() output is a Map[String, Array[String]], you're going to have to reach into the map's values before applying mkString to the Array.

This is one way ...

println(words.groupBy(_.substring(0, 1)).mapValues(_.mkString))

... but it's a little more idiomatic (and perhaps easier to read the output) if you do it this way ...

words.groupBy(_.substring(0, 1)).mapValues(_.mkString).foreach(println)
Comments