4

I need to remove some sets from a master set. The following code shows the concept I intend to work but it is generating warnings for deprecation. The suggestion given by Scala is not useful as I want to repeatedly update master set. Could anyone suggest a simple alternative please?

scala> var setM = scala.collection.mutable.Set[Int](1, 2, 3, 4, 5)
setM: scala.collection.mutable.Set[Int] = HashSet(1, 2, 3, 4, 5)

scala> var setX = scala.collection.mutable.Set[Int](3, 4)
setX: scala.collection.mutable.Set[Int] = HashSet(3, 4)

scala> setM = setM -- setX
                   ^
       warning: method -- in trait SetOps is deprecated (since 2.13.0): Consider requiring an immutable Set mutated setM

scala> setM
res0: scala.collection.mutable.Set[Int] = HashSet(1, 2, 5)
4

1 回答 1

3

The warning is pretty clear:

method -- in trait SetOps is deprecated (since 2.13.0): Consider requiring an immutable Set

It can be seen here. You can do the same with immutable set:

var setM = Set(1, 2, 3, 4, 5)
val setX = Set(3, 4)
setM = setM -- setX
println(setM)

Code run at Scastie.

Having said that, using vars is not recommended in Scala. I'd do:

val setM = Set(1, 2, 3, 4, 5)
val setX = Set(3, 4)
val updatedSetM = setM -- setX
println(updatedSetM)

Which results with:

HashSet(5, 1, 2)

Code run at Scastie.

于 2021-02-09T08:52:09.233 回答