将可变映射转换为不可变映射 [英] Converting mutable to immutable map

查看:66
本文介绍了将可变映射转换为不可变映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private[this]object MMMap extends  HashMap[A, Set[B]] with MultiMap[A, B]

如何将其转换为不可变的?

How convert it to immutable?

推荐答案

不可变的层次结构不包含MultiMap,因此您将无法以相同的方便语法使用转换后的结构.但是,如果您乐于处理键/值集对,则:

The immutable hierarchy doesn't contain a MultiMap, so you won't be able to use the converted structure with the same convenient syntax. But if you're happy to deal with key/valueset pairs, then:

如果只想使用可变的HashMap,则可以在2.8中使用x.toMap或在2.7中使用collection.immutable.Map(x.toList: _*).

If you just want a mutable HashMap, you can just use x.toMap in 2.8 or collection.immutable.Map(x.toList: _*) in 2.7.

但是,如果您希望整个结构是不可变的-包括基础集合!-那么您必须做更多的事情:您需要沿途转换这些集合.在2.8版中:

But if you want the whole structure to be immutable--including the underlying set!--then you have to do more: you need to convert the sets along the way. In 2.8:

x.map(kv => (kv._1,kv._2.toSet)).toMap

在2.7版中:

collection.immutable.Map(
  x.map(kv => (kv._1,collection.immutable.Set(kv._2.toList: _*))).toList: _*
)

这篇关于将可变映射转换为不可变映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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