Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Iterable

Tags:

iterable

scala

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?

like image 276
synapse Avatar asked Oct 23 '13 21:10

synapse


1 Answers

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)
like image 81
dhg Avatar answered Nov 14 '22 16:11

dhg