Scala - initializing mutable Maps and exposing them as immutable

前端 未结 2 1022
抹茶落季
抹茶落季 2021-01-16 01:47

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 eter

相关标签:
2条回答
  • 2021-01-16 02:07

    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.

    0 讨论(0)
  • 2021-01-16 02:21

    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)
    
    0 讨论(0)
提交回复
热议问题