简体   繁体   中英

Scala - initializing mutable Maps and exposing them as immutable

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?

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.

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.

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).

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

Something like:

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)

I think using var s of immutables rather that val s of mutables, evolving the var collections according to my initialization logic, can be the optimal pattern wherever applicable. No duplicate collections, no code to convert from immutable to mutable, clear type definitions at the top of the Class...

However, it is my understanding that this functional way trades-off with run time efficiency, as mutable collections can provide better modification performance when running modification logic on them while building them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM