Making a class iterable

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Making a class iterable

Alan Burlison
I have a simple class that just wraps around a Seq and I want the
contained Seq to be iterable. I've looked in the docs and there seem to
be quite a few deprecated classes/traits related to this, e.g.
IterableProxy, IterableForwarder but I *think* the correct one to use is
Iterable, is that right?

I notice that as well as requiring you to implement the iterator()
method there's the following rather cryptic comment:

"They also need to provide a method newBuilder which creates a builder
for collections of the same kind."

but there's no corresponding abstract method so I'm wondering if that's
mandatory or optional? Also, what should the signature of the newBuilder
method be?

I also found :

http://daily-scala.blogspot.co.uk/2010/04/creating-custom-traversable.html

which explains about how to build on top of Traversable. The main
advantage seems to be that you can control the type of collection
returned by the various collection methods. I suspect that won't be
necessary for my particular use case however.

I also want an 'wrap around' iterator for the same collection - it
contains a set of transformations that in some circumstances need to be
applied over and over until an external condition is met. For example
the collection might contain 2 transformations that need to be applied
10 times in total, so each transformation will be used 5 times. Is the
best way of doing that to just subclass Iterator with AbstractIterator?
The only issue is they contain methods such as count() and length() that
don't make any sense in the context of a 'wrap around' collection such
as this, and will never return if called. Are there any better
alternatives in the library?

Thanks,

--
Alan Burlison
--

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|

Re: Making a class iterable

Seth Tisue
without newBuilder, operations don’t return the outer type:

scala> class Wrapper[T](wrapped: Seq[T]) extends Iterable[T] { override def iterator = wrapped.iterator }
defined class Wrapper

scala> new Wrapper(List(1, 2, 3))
res0: Wrapper[Int] = (1, 2, 3)

scala> res0.map(_ + 1) // doesn’t return a Wrapper
res1: Iterable[Int] = List(2, 3, 4)

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.