This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Most elegant way to write an array iterator?

2 replies
Kenneth McDonald
Joined: 2009-01-11,
User offline. Last seen 42 years 45 weeks ago.

Scala doesn't seem to ship with an ArrayIterator. It's easy enough to
write one using next and hasNext of course, but I'm wondering if there
are any neat Scala tricks that make writing an Array Iterator a one-
liner (or at least, a fewer-liner :-) )

Thanks,
Newbie Ken

DRMacIver
Joined: 2008-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: Most elegant way to write an array iterator?
On Mon, Jan 19, 2009 at 7:32 AM, Kenneth McDonald <kenneth [dot] m [dot] mcdonald [at] sbcglobal [dot] net> wrote:
Scala doesn't seem to ship with an ArrayIterator. It's easy enough to write one using next and hasNext of course, but I'm wondering if there are any neat Scala tricks that make writing an Array Iterator a one-liner (or at least, a fewer-liner :-) )

scala> Array(1, 2, 3)
res0: Array[Int] = Array(1, 2, 3)

scala> res0.elements
res1: Iterator[Int] = non-empty iterator

Rich Dougherty 2
Joined: 2009-01-19,
User offline. Last seen 42 years 45 weeks ago.
Re: Most elegant way to write an array iterator?
Hi Ken

Array extends Seq, so there are plenty of ways to iterate over its contents. But if you want an Iterator for some reason then you can get one with the 'elements' method.

scala> val a = Array(1, 2, 3, 4)
a: Array[Int] = Array(1, 2, 3, 4)
scala> val i = a.elements
i: Iterator[Int] = non-empty iterator
scala> i.hasNext
res0: Boolean = true
scala> i.next
res1: Int = 1
scala> i.next
res2: Int = 2
scala> i.next
res3: Int = 3
scala> i.next
res4: Int = 4
scala> i.hasNext
res5: Boolean = false

This is, of course, a scala.Iterator. If you're after a java.util.Iterator then you'll probably need to implement one yourself.

Rich

On Mon, Jan 19, 2009 at 8:32 PM, Kenneth McDonald <kenneth [dot] m [dot] mcdonald [at] sbcglobal [dot] net> wrote:
Scala doesn't seem to ship with an ArrayIterator. It's easy enough to write one using next and hasNext of course, but I'm wondering if there are any neat Scala tricks that make writing an Array Iterator a one-liner (or at least, a fewer-liner :-) )

Thanks,
Newbie Ken

--
http://www.richdougherty.com/

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland