scalacollections

Output of Iterable.sliding as Tuple


The method sliding on collections returns a sliding window of given size in the form of X[Iterable[A]] with X being the type of the collection and A the element type. Often I need two or three elements and I prefer to have them named. One ugly workaround for sliding(2) is the following:

points.sliding(2).foreach{ twoPoints =>
      val (p1,p2) = (twoPoints.head,twoPoints.last)
      //do something
}

This sucks and only works for two elements. Also note that

(a,b) = (twoPoints(0),twoPoints(1))

doesn't work.


Solution

  • I did a lot of that in this answer just last week.

    points.sliding(2).foreach { case X(p1, p2) => ... }
    

    If points is an Array, then replace X with Array. If it is a List, replace X with List, and so on.

    Note that you are doing a pattern match, so you need to {} instead of () for the parameter.