MetallicPriest
MetallicPriest

Reputation: 30765

How can I iterate a scala collection using a loop?

I know I can use the x.foreach{ ... } syntax, but I want to explicity use a loop. How can I do that in Scala? I tried to use the following code, but it complains that hasNext and next are not members of the Iterable[T].

while (it.hasNext)
  println("\t" + it.next.toString()) 

Upvotes: 0

Views: 161

Answers (3)

elm
elm

Reputation: 20415

Consider also map,

it.iterator.map(i => "\t" + i.toString())

as well as a for comprehension,

for (i <- it.iterator) yield "\t" + i.toString()

Upvotes: 0

Dmitry  Meshkov
Dmitry Meshkov

Reputation: 931

use

val iter = it.iterator
while (iter.hasNext) {
  println("\t" + iter.next.toString())
}

Upvotes: 2

Gregor Ra&#253;man
Gregor Ra&#253;man

Reputation: 3081

Iterable does not have next nor hasNext, Iterator has.

So your code needs to change to something like this:

val i = it.iterator
while (i.hasNext) println("\t" + i.next.toString())

Note however that this is not idiomatic Scala at all.

You could achieve the same with println(it.mkString("\t","\t",""))

Upvotes: 2

Related Questions