問題描述
我只想使用一些并發(fā)的 Set(似乎根本不存在).Java 使用 java.util.concurrent.ConcurrentHashMap
來實(shí)現(xiàn)該行為.我想在 Scala 中做類似的事情,所以我創(chuàng)建了 Scala HashMap(或 Java ConcurrentHashMap)的實(shí)例并嘗試添加一些元組:
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))
這當(dāng)然會導(dǎo)致編譯過程崩潰,因?yàn)?Unit 是抽象的和最終的.
This of course crashed the process of compilation as Unit is abstract and final.
如何做到這一點(diǎn)?我應(yīng)該改用 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
類型的值只有一個(gè)()
,在底層運(yùn)行時(shí)系統(tǒng)中不被任何對象表示.
There is only one value of type
Unit
,()
, and it is not represented by any object in the underlying runtime system.
這篇關(guān)于如何在 Scala 中實(shí)例化 Unit?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!