how to instantiate Unit in Scala?(如何在 Scala 中实例化 Unit?)
问题描述
我只想使用一些并发的 Set(似乎根本不存在).Java 使用 java.util.concurrent.ConcurrentHashMap
来实现该行为.我想在 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.
感谢您的帮助
推荐答案
你可以使用类型为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 -> ())
这是来自 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Scala 中实例化 Unit?


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01