Iterable implementation

How to implement Scala equivalent of Java Iterable<T> and C # IEnumerable<T> ? Basically, I want my collection to be capable of displaying, filtering, etc. What features should extend a collection class and are there simple ways (e.g. yield return and yield break in C #) to create an enumerator?

+8
scala iterable
source share
3 answers

Implement the Iterable attribute. All that is required is the iterator method. All other methods ( map , filter , etc.) are provided free of charge.

 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) 
+13
source share

You can use the scala.collection.Iterable or its immutable version, which are quite comprehensive and powerful. Hope this helps.

0
source share

As for counters, there is an enumeration in Scala, but the use of closed features + derived classes seems more flexible, for example:

 sealed trait MyEnum { lazy val value = 0 } case object MyEnumA extends MyEnum { override lazy val value = 1 } case object MyEnumB extends MyEnum { override lazy val value = 2 } scala> val a = MyEnumB a: MyEnumB.type = MyEnumB scala> a.value res24: Int = 2 scala> val l = List(MyEnumA,MyEnumB) l: List[Product with Serializable with MyEnum] = List(MyEnumA, MyEnumB) scala> l.map(_.value) res29: List[Int] = List(1, 2) 

You can use these objects without any internal structure if you do not need to match them with anything other than your string representations:

 sealed trait MyEnum case object MyEnumA extends MyEnum case object MyEnumB extends MyEnum scala> val a = MyEnumA a: MyEnumA.type = MyEnumA scala> a.toString res21: String = MyEnumA scala> val l = List(MyEnumA,MyEnumB) l: List[Product with Serializable with MyEnum] = List(MyEnumA, MyEnumB) scala> l.map(_.toString) res30: List[String] = List(MyEnumA, MyEnumB) 
0
source share

All Articles