Scala Trait Fun

I forget where I found this #Scala snippet:

trait RichIterableOps[A] {

  // required method
  def iterator: Iterator[A]

  def foreach(f: A => Unit) = {
    val iter = iterator
    while (iter.hasNext) f(iter.next)
  } 

  def foldLeft[B](seed: B)(f: (B, A) => B) = {
    var result = seed
    foreach(e => result = f(result, e))
    result
  } 
}

val richSet = new HashSet[Int] with RichIterableOps[Int]
richSet.add(1); richSet.add(2)
richSet.foldLeft(1)((x,y) => x+y)

-m

04/15/09 at 1:18pm