Set 的 Scala Nil 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10506226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:09:46  来源:igfitidea点击:

Scala Nil equivalent for Set

scalascala-collections

提问by Rand

Is there an equivalent of Nilfor Setin scala?

是否有一个等同NilSet在Scala呢?

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

我尝试将Nil用作 的值Set,但出现错误(预期是因为类型NilList

Thanks

谢谢

回答by Rex Kerr

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

Set.empty是那一套吗?虽然你不能直接得到它,但事实证明它只是Set伴随对象中的一个私有对象(很明显,它被称为EmptySet)。所有这一切Set.empty确实是返回与集合强制转换为正确的类型。

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

它是通过这种方式完成的,而不是 with Nil,因为集合的参数是不变的。 Nilis List[Nothing](),但您不能向 a 添加任何内容Set[Nothing]()

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

如果需要指定空集的类型,可以使用 eg Set.empty[String]

回答by paradigmatic

You can use Set.emptyor simply Set().

您可以使用Set.empty或简单地使用Set().

回答by Chris Shain

I think you are looking for Set.empty

我想你正在寻找 Set.empty