问题
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))
This of course crashed the process of compilation as Unit is abstract and final.
How to make this work? Should I use Any
/AnyRef
instead? I must ensure nobody inserts any value.
Thanks for help
回答1:
You can just use ()
whose type is 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 -> ())
This is a comment taken from Unit.scala:
There is only one value of type
Unit
,()
, and it is not represented by any object in the underlying runtime system.
来源:https://stackoverflow.com/questions/26563213/how-to-instantiate-unit-in-scala