While working through converting some Java code over to Scala, I discovered while there is a contains
method for Scala's Set
, there isn't a containsAll
method. Am I just missing the correct method name?
Here's a bit of code I worked up to fill in the gap so I could quickly get back to working. Is it sufficient, or am I missing some subtlety?
def containsAll[A](set: Set[A], subset: Set[A]): Boolean =
if (set.size >= subset.size)
subset.forall(a => set.contains(a))
else
false
There is subsetOf
, which tests whether or not the elements of a Set
are contained within another Set
. (Kind of the reverse in terms of the expression)
val set = Set(1,2,3,4)
val subset = Set(1,2)
scala> subset.subsetOf(set)
res0: Boolean = true
scala> set.subsetOf(subset)
res1: Boolean = false