問題描述
我只想使用一些并發的 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模板網!