How to instantiate a module in Scala?

All I wish is to use some parallel Set (which does not exist at all). Java uses java.util.concurrent.ConcurrentHashMap<K, Void> to achieve this behavior. I would like to make sth similar 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, broke the compilation process, as the Unit is abstract and final.

How to make this work? Should I use Any / AnyRef instead? I have to ensure that no one inserts any value.

thanks for the help

+6
source share
1 answer

You can simply 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 execution system.

+11
source

Source: https://habr.com/ru/post/977217/


All Articles