Scala - initializing mutable Maps and exposing them as immutable

前端 未结 2 1021
抹茶落季
抹茶落季 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: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)
    

提交回复
热议问题