Given that Seq.view
returns a SeqView
, I would have expected Set.view
to return a SetView
, but no such view exists; Set.view
instead returns an IterableView
.
Unfortunately, IterableView
is missing some methods, such as contains
. Compare these, 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 particular reason why no SetView
class exists?
Also, is there any reason why Iterable
doesn't have a contains
method (given this is basically a special case of find)?
Given the situation above, is there a better alternative to this when working with sets (in other words, what is the best practice in Scala):
Set(1, 2, 3).view.map(_ * 2).find(_ == 4).isDefined
There is no SetView
because views are a pain in the neck to implement and test, and that effort is less worth it since the nice properties of sets generally require you to have already eagerly created the entire set (e.g. O(1)
or O(log n)
lookup).
contains
isn't in Iterable
precisely because Set
extends Iterable
and a Set
contains
should not type check unless you ask for something that could be in the set. Since Iterable
is covariant, its contains
would have to admit you asking for anything (as the contains
for Seq
does).
As a workaround, you can note that contains(x)
does the same thing as exists(_ == x)
, and exists
is on Iterable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With