Scala - 初始化可变映射并将它们公开为不可变 [英] Scala - initializing mutable Maps and exposing them as immutable

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

问题描述

对于 Class 初始化和填充私有可变映射,然后将它们公开为不可变映射,是否有任何好的"代码模式?或者,在这种情况下,我是否应该永远为自己的不当行为感到后悔?

Is there any "good" code pattern for a Class initializing and populating private mutable Maps, and then exposing them as immutable ones? Or should I just eternally regret my functional misconduct in such cases?

在某个类中,我将一些 Map 初始化为可变的,因为初始化它们的逻辑不太适合,在这种情况下,使用纯可变创建方法.或者,我只是懒得对其进行一成不变的建模.

In a certain Class, I am initializing some Maps as mutable ones, as the logic for initializing them does not fit very naturally, in this one case, with a pure mutable creation approach. Or, I was just lazy to model it immutably.

现在,我得到了 Scala 丑陋的代码 - 在所有初始化计算之后,我将可变映射复制转换为不可变映射(主要通过 .toMap).这已经很丑了,因为 (1) 代码有两倍的 Map 并且双重命名感觉有点不对劲,并且 (2) 转换线看起来比我希望的要复杂.

Now, I get Scala ugly code - after all the initialization computation, I copy-convert the mutable Maps into immutable ones (mostly through .toMap). This is already ugly as (1) the code has double the Maps and the double naming feels a bit off, and (2) the conversion lines look more involved than I'd hope for.

另外(3),我不喜欢生成的不可变 Maps 的类型定义现在只能驻留在代码的底部,因为它们只能在初始化计算之后声明(或者,它们可以是定义 lazy 并移动到顶部?仍然不完全优雅).

Additionally (3), it is to my disliking that the type definitions of the resulting immutable Maps, can only reside at the bottom of the code now, as they can only be declared after the initialization computation (or, can they be defined lazy and move to the top? still not entirely elegant).

有什么方法可以优雅地包装可变 Maps 初始化代码?

Any way to elegantly wrap up around mutable Maps initialization code?

推荐答案

类似:

scala> class X {
     |   private val mb = collection.immutable.Map.newBuilder[String, Int]
     |   def m = mb.result
     |   mb += ("a" -> 1)  // stuff
     | }
defined class X

scala> new X().m
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1)

这篇关于Scala - 初始化可变映射并将它们公开为不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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