Why does Scala have a SeqView but not a SetView?

Given that Seq.view returns a SeqView , I would expect Set.view return a SetView , but such a view does not exist; Set.view instead returns an IterableView .

Unfortunately, IterableView lacks some methods, for example, contains . Compare them, for example:

 Seq(1, 2, 3).view.map(_ * 2).contains(4) // returns true Set(1, 2, 3).view.map(_ * 2).contains(4) // error 

Is there any special reason why there is no SetView class?

Also, is there any reason why Iterable does not have a contains method (given that this is basically a special case of the search)?

Given the situation above, is there a better alternative to this when working with sets (in other words, which works best for Scala):

 Set(1, 2, 3).view.map(_ * 2).find(_ == 4).isDefined 
+5
source share
1 answer

There is no SetView , because views are a pain in the neck for implementation and testing, and this effort is less than worth it, because the good properties of sets usually require that you look forward to creating the whole set (for example, O(1) or O(log n) ).

contains not in Iterable precisely because Set extends Iterable and Set contains should not enter validation unless you ask for something that might be in the set. Since Iterable is covariant, its contains would have to admit that you are asking for something (as contains does for Seq ).

As a workaround, you may notice that contains(x) does the same thing as exists(_ == x) , and exists is on Iterable .

+2
source

Source: https://habr.com/ru/post/1204757/


All Articles