4. Nesting and subsections

A Config subsection is itself a Config instance - it’s easy to group your keys therefore.

Here’s a sample file we’ll be discussing:

xx.a.z1 = alpha-xx
xx.a.z2 = beta-xx
xx.b.z3 = gamma-xx
xx.b.z4 = delta-xx

[yy]
a.z1 = alpha-yy
a.z2 = beta-yy

[zz]
a.z1 = alpha-zz
a.z2 = beta-zz

There are two ways to deal with sections and hierarchies of settings.

Prefixes

The crudest is simply by choosing a common prefix on all the keys in the group. Here’s how to extract a sub-section and a sub-sub-section, by means of the startingWith method:

  val xx: Config = config.startingWith("xx.") // keys a.z1, a.z2, b.z3, b.z4
  val xxa: Config = xx.startingWith("a.") // keys z1, z2

INI File Sections

If you prefer, you can use ‘INI’-file syntax for the sections instead. If the config file contains [yy] on a line as shown above, all the items below that line are separated out like this:

  val yy: Config = config.section("yy") // keys a.z1, a.z2

Note that a dot separates the section name from the keys it contains. Therefore, a directly equivalent way of extracting this section is:

  val yy: Config = config.startingWith("yy.") // keys a.z1, a.z2

Because INI files are supported simply by prepending a section name onto each of the keys following it, with a dot separator, you can choose freely between the section approach and the equivalent startingWith approach. The only difference between the two is that section implies an extra dot whereas startingWith does not.