Reputation: 865
When iterating through a map like so:
val powers = Map("Spark man" -> "Electricity", "Bubble man" -> "Fires Bubbles", "Guts man" -> "No idea")
println(powers.size)
println(powers.foreach(man => println(man._1 + " -> " + man._2)))
Why does it seem to produce a fourth item when printing as such:
3
Spark man -> Electricity
Bubble man -> Fires Bubbles
Guts man -> No idea
()
With the braces on the last line being the part confusing me.
As you can probably tell I'm quite new to the language, so it's likely something simple, but I can't seem to find anything relating to this.
Upvotes: 2
Views: 130
Reputation: 144136
powers.foreach(man => println(man._1 + " -> " + man._2)
returns the value of type Unit
- this value is displayed as ()
.
You are printing this value as well as each pair in the map, so your code is effectively the same as
val u: Unit = powers.foreach(man => println(man._1 + " -> " + man._2)
println(u)
Upvotes: 4
Reputation: 4860
You have in the last line 2 println's
println(powers.foreach(man => println(man._1 + " -> " + man._2)))
The inner println
is printing the 3 man lines and the outer one is printing the ()
Upvotes: 5