将元素添加到作为映射值的 Scala 集 [英] Adding element to a scala set which is a map value

查看:46
本文介绍了将元素添加到作为映射值的 Scala 集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Scala 中有以下地图:

I have the following map in Scala:

var m = Map[Int,Set[Int]]()
m += 1 -> Set(1)
m(1) += 2

我发现最后一行不起作用.我收到错误:重新分配给 val".

I've discovered that the last line doesn't work. I get "error: reassignment to val".

所以我尝试了

var s = m(1)
s += 2

然后当我将 m(1)s 添加 2 后进行比较时,它们的内容是不同的.那么如何将元素添加到作为地图值的集合中?

Then when I compared m(1) with s after I added 2 to it, their contents were different. So how can I add an element to a set which is the value of a map?

我有 Java/C++ 背景,所以我的尝试对我来说似乎很自然,但显然它不在 Scala 中.

I come from a Java/C++ background so what I tried seems natural to me, but apparently it's not in Scala.

推荐答案

您可能正在使用 immutable.Map.您需要使用mutable.Map,或者替换该集合而不是使用另一个不可变映射对其进行修改.

You're probably using immutable.Map. You need to use mutable.Map, or replace the set instead of modifying it with another immutable map.

这是对可变与不可变数据结构的描述的参考.

所以...

import scala.collection.mutable.Map
var m = Map[Int,Set[Int]]()
m += 1 -> Set(1)
m(1) += 2

这篇关于将元素添加到作为映射值的 Scala 集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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