29

Is there an equivalent of Nil for Set in scala?

I tried using Nil as a value for Set, but I got an error (expected since the type of Nil is List)

Thanks

leedm777
  • 23,444
  • 10
  • 58
  • 87
Rand
  • 991
  • 3
  • 11
  • 20

3 Answers3

40

Set.empty is that set; although you can't get at it directly, it turns out that it is just a private object in the Set companion object (called, obviously enough, EmptySet). All that Set.empty does is return that set with a cast to the correct type.

It is done this way, instead of with Nil, because sets are invariant in their parameters. Nil is List[Nothing](), but you couldn't add anything to a Set[Nothing]().

If you need to specify the type of your empty set, you can use e.g. Set.empty[String].

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
12

You can use Set.empty or simply Set().

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
7

I think you are looking for Set.empty

Chris Shain
  • 50,833
  • 6
  • 93
  • 125