我只想使用一些并发的 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.
这篇关于如何在 Scala 中实例化 Unit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 Java-8 Streams API 将字符串列表转换为 MapConvert List of Strings into Map using Java-8 Streams API(使用 Java-8 Streams API 将字符串列表转换为 Map)
从 JSON 获取数据Getting data from JSON(从 JSON 获取数据)
javalinkedhashmap迭代java linkedhashmap iteration(javalinkedhashmap迭代)
将对象列表转换为 MapConverting a list of objects to Map(将对象列表转换为 Map)
用一个固定的Key对应一个HashSet创建一个HashMap.出Create a HashMap with a fixed Key corresponding to a HashSet. point of departure(用一个固定的Key对应一个HashSet创建一个HashMap.出发点)
HttpMessageConverter 异常:RestClientException:无法写入请HttpMessageConverter exception : RestClientException: Could not write request: no suitable HttpMessageConverter found(HttpMessageConverter 异常:RestC