Scala Nil equivalent for Set

一世执手 提交于 2019-12-03 10:45:21

问题


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


回答1:


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




回答2:


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




回答3:


I think you are looking for Set.empty



来源:https://stackoverflow.com/questions/10506226/scala-nil-equivalent-for-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!