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.
I did a lot of that in this answer just last week.
If
pointsis anArray, then replaceXwithArray. If it is aList, replaceXwithList, and so on.Note that you are doing a pattern match, so you need to
{}instead of()for the parameter.