Set 的 Scala Nil 等价物 [英] Scala Nil equivalent for Set

查看:48
本文介绍了Set 的 Scala Nil 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 中是否有与 Nil 等效的 Set ?

Is there an equivalent of Nil for Set in scala?

我尝试使用 Nil 作为 Set 的值,但出现错误(预期,因为 Nil 的类型是 列表)

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

谢谢

推荐答案

Set.empty 就是那个集合;虽然你不能直接得到它,但事实证明它只是 Set 伴随对象中的一个私有对象(很明显,它被称为 EmptySet).Set.empty 所做的就是通过强制转换将该集合返回到正确的类型.

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.

以这种方式完成,而不是使用 Nil,因为集合在其参数中不变.NilList[Nothing](),但是你不能向 Set[Nothing]() 添加任何东西.

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

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

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

这篇关于Set 的 Scala Nil 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆