如何在 Scala 中实例化 Unit? [英] how to instantiate Unit in Scala?

查看:34
本文介绍了如何在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆