Java – how to instantiate unit in scala?

All I want is to use some concurrent sets (they don't seem to exist at all) Java uses Java util. concurrent. Concurrent HashMap < K, void > implements this behavior I want to do similar things in Scala, so I created an 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 destroys the compilation process, because unit is abstract and final

How to make this work? Should I use any / anyref? I have to make sure no one inserts any value

Thank you for your help

Solution

You can 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 from unit Scala comments:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>