How to implement Scala equivalent to Java Iterable<T>
and C# IEnumerable<T>
? Basically, I want my collection to be mappable, filterable etc. What traits should the collection class extend and are there easy ways (something like yield return
and yield break
in C#) to create enumerator?
Implement the Iterable
trait. All that is required is the iterator
method. All the other methods (map
, filter
, etc) come for free.
class MyIterable[T](xs: Vector[T]) extends Iterable[T] {
override def iterator = xs.iterator
}
val a = new MyIterable(Vector(1,2,3))
a.map(_+1) // res0: Iterable[Int] = List(2, 3, 4)
a.filter(_%2==1) // res1: Iterable[Int] = List(1, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With