how to instantiate Unit in Scala?

2019-02-17 08:36发布

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条回答
何必那么认真
2楼-- · 2019-02-17 09:18

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.

查看更多
登录 后发表回答