how to instantiate Unit in Scala?

流过昼夜 提交于 2020-01-11 05:13:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!