List(1,2,3,4).sliding(2).map({ case List(a, b) => a < b }).forall(identity)
compiles and returns true (albeit with a warning that the match is not exhaustive).
List(1,2,3,4).view
.sliding(2).map({ case List(a: Int, b: Int) => a < b }).forall(identity)
compiles (so long as we include the type annotations for a and b) but throws a MatchError:
scala.MatchError: SeqViewC(...) (of class scala.collection.SeqViewLike$$anon$1)
at $anonfun$1.apply(<console>:12)
at $anonfun$1.apply(<console>:12)
at scala.collection.Iterator$$anon$19.next(Iterator.scala:335)
at scala.collection.Iterator$class.forall(Iterator.scala:663)
at scala.collection.Iterator$$anon$19.forall(Iterator.scala:333)
Why?
That’s interesting, the list extractor
List.unapplySeqis not able to extractSeqViewLikeobjects, which is why you get a match error. But on the other handSeqcan. You can see that like this:So a fix to your second line would be:
So the issue is that
List(1,2,3,4).viewreturns aSeqView.Note that
slidingalready returns anIterator, so List(1,2,3,4).sliding(2) is lazy is that sense. May beviewis not necessary.