Kevin Meredith
Kevin Meredith

Reputation: 41939

Prepending Items to Scala Set

In Scala I can prepend items to a List via:

scala> 1 :: 2 :: 3 :: Nil
res16: List[Int] = List(1, 2, 3)

What's the equivalent :: operator for a Scala Set?

Upvotes: 0

Views: 642

Answers (1)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179219

I believe you're looking for +. It's not called "prepend", but "add". The reason is that Set doesn't guarantee an ordering for the inserted elements.

scala> val s = Set(1, 2, 3)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> s + 3
res0: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> s + 4
res1: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)

scala> s + 4 + 5
res2: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

Upvotes: 5

Related Questions