0

I've this codesnippet:

val O = Array(3, "str")
for (o <- O) print(o)
println("\n===")
for (_ <- O) print(_)
println("\n===")

It prints

3str
===

===

Why the second for+print(_) doesn't print anything? Any explanations?

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

1 Answers1

4

for (_ <- O) translation: Pull each element from O but don't assign them to anything. Just throw those values away.

print(_) translation: For each unused element from O, use eta expansion to turn the print() method into a proper function that does the same thing. Then throw it away.

Added reference: What are all the uses of an underscore in Scala?

jwvh
  • 50,871
  • 7
  • 38
  • 64