Scala Nil equivalent for Set

后端 未结 3 616
鱼传尺愫
鱼传尺愫 2021-02-05 03:39

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 s

相关标签:
3条回答
  • 2021-02-05 04:12

    I think you are looking for Set.empty

    0 讨论(0)
  • 2021-02-05 04:16

    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].

    0 讨论(0)
  • 2021-02-05 04:23

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

    0 讨论(0)
提交回复
热议问题