Checking how many elements a set contains
13,026
You just need the size
method on a Set:
scala> Set(1).size
res0: Int = 1
scala> Set(1,2).size
res1: Int = 2
See also the documentation for Set.
Let's say your other function is called getSet
. So all you need to do is call it, then check the size of the resulting Set
, and return a value depending on that size. For example, I shall assume that if the set's size is 1, we need to return a special value (a Set containing the value 99) - but just replace this with whatever specific result you actually need to return.
def mySet = {
val myset = getSet()
if (myset.size == 1) Set(99) // return special value
else myset // return original set unchanged
}
Author by
user2947615
Updated on June 04, 2022Comments
-
user2947615 almost 2 years
I need to write a function that returns true if a set (this set is the output of another function) contains 1 element and otherwise it leaves the set as it is.
For example:
Set(1) returns a specific result and Set(2,4) returns the set as it is.
How can I check how many elements a set contains?
-
Kevin Meredith over 10 yearsRather than use special return types that may confuse due to being magical, why not use a return type of
Option[Set[A]]
whereA
isInt
here? -
DNA over 10 yearsAgreed, that may well be a better design (depending on what the OP is actually trying to achieve)