Monday 14 March 2016

Parsing Map Structure from Config File

In some cases, we want to set a map relationship in config file, and keep their orders in our app.
In application.conf, we have a map like below.
Note: The key must be a string, can't contain any variables.
If it contains '.', a double quota is needed.

pairs = [
    {"c.json": ccc},
    {"a.json": aaa},
    {"b.json": bbb}
  ]

import scala.collection.immutable.ListMap
lazy val inputPairs : ListMap[String, String] = {

      val list : Iterable[ConfigObject] = stageConfig
        .getObjectList("pairs")
        .toList

     val map = for {
        item : ConfigObject = list
        entry : Entry[String, ConfigValue] = item.entrySet().toList
        col = entry.getKey
        func =  entry.getValue.unwrapped().toString
      } yield (col, func)

      map.map(identity)(collection.breakOut)
    }  


Note: Here we use immutable.ListMap to keep the input order.
Otherwise, Map will return uncertain orders.

In the definition of map:
def map[B, That](f : (A) => B)(implicit bf : CanBuildFrom[Repr, B, That]) : That 
The first is your function and the second is an implicit. If you do not provide that implicit, Scala will choose the most specific one available.

breakOut can help to skip the intermediary List and collect the results directly into a Map


The definition of breakOut:
def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
  new CanBuildFrom[From, T, To] {
    def apply(from: From) = b.apply() ; def apply() = b.apply()
  }


Reference:


No comments:

Post a Comment