如何在 Scala 中实例化 Unit?

2022-01-08 00:00:00 set scala concurrency hashmap java

我只想使用一些并发的 Set(似乎根本不存在).Java 使用 java.util.concurrent.ConcurrentHashMap 来实现该行为.我想在 Scala 中做类似的事情,所以我创建了 Scala HashMap(或 Java ConcurrentHashMap)的实例并尝试添加一些元组:

All I desire is to use some concurrent Set (that appears not to exist at all). Java uses java.util.concurrent.ConcurrentHashMap<K, Void> to achieve that behavior. I'd like to do sth similar in Scala so I created instance of Scala HashMap (or Java ConcurrentHashMap) and tried to add some tuples:

val myMap = new HashMap[String, Unit]()
myMap + (("myStringKey", Unit))

这当然会导致编译过程崩溃,因为 Unit 是抽象的和最终的.

This of course crashed the process of compilation as Unit is abstract and final.

如何做到这一点?我应该改用 Any/AnyRef 吗?我必须确保没有人插入任何值.

How to make this work? Should I use Any/AnyRef instead? I must ensure nobody inserts any value.

感谢您的帮助

推荐答案

你可以使用类型为Unit():

scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> val myMap = new HashMap[String, Unit]()
myMap: scala.collection.mutable.HashMap[String,Unit] = Map()

scala> myMap + ("myStringKey" -> ())
res1: scala.collection.mutable.Map[String,Unit] = Map(myStringKey -> ())

这是来自 Unit.scala:

Unit类型的值只有一个(),在底层运行时系统中不被任何对象表示.

There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system.

相关文章