如何在Scala中实例化Unit? [英] how to instantiate Unit in Scala?
问题描述
我想要的是使用一些并发的Set(根本不存在)。 Java使用 java.util.concurrent.ConcurrentHashMap< K,Void>
来实现这种行为。我想在Scala中做类似的,所以我创建了Scala HashMap(或Java ConcurrentHashMap)的实例,并试图添加一些元组:
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))
这当然会导致编译过程崩溃,因为Unit是抽象的和最终的。
This of course crashed the process of compilation as Unit is abstract and final.
如何使这个工作?我应该使用 Any
/ AnyRef
吗?我必须确保没有人插入任何值。
How to make this work? Should I use Any
/AnyRef
instead? I must ensure nobody inserts any value.
感谢您的帮助
推荐答案
您可以使用类型为
的()
:
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 -> ())
这是从 Unit.scala
:
Unit
,()
只有一个值,并且它不是由底层运行时系统。
There is only one value of type
Unit
,()
, and it is not represented by any object in the underlying runtime system.
这篇关于如何在Scala中实例化Unit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!