matanox
matanox

Reputation: 13686

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?

Upvotes: 1

Views: 2216

Answers (2)

som-snytt
som-snytt

Reputation: 39577

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)

Upvotes: 3

matanox
matanox

Reputation: 13686

I think using vars of immutables rather that vals 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.

Upvotes: -1

Related Questions