-
Notifications
You must be signed in to change notification settings - Fork 19
BasicOperations
Here are some options to create a configuration:
/* Empty configuration */
val config = Configuration()
/* Configuration from key and values */
val config = Configuration( "name" -> "Bob", "age" -> 42, "married" -> false )
/* Configuration from Map[String,String] */
val data = Map( "name"->"Bob", "age"->"42", "married"->"false" )
val config = new Configuration( data )Note that first and second examples use the companion object while third example uses the new keyword.
To load a configuration from a file (or an URL, InputStream, etc.) see InputOutput
Configuration use the same semantic as Map for accession a value. Let a configuration instance config contain the configuration:
name = Bob
age = 42
married = true
The values can be retrieved with the apply method. If a key is missing, NoSuchElementException will be thrown. A type must be provided for conversion:
val name = config[String]( "name" ) // name =="Bob"
val age = config[Int]( "age" ) // age == 42
val isMarried = config[Boolean]( "married" ) // isMarried == true
val hasChildren = config[Boolean]( "children" ) // throws an exceptionThe methods contains can be used to check if a key is present:
if( config contains "children" && config[Boolean]( "children" ) ) {
println( name + " has children." )
}Options to values can be retrieved with the get method. If a key is missing, None will be returned:
val name = config.get[String]( "name" ) // name == Some("Bob")
val age = config.get[Int]( "age" ) // age == Some(42)
val isMarried = config.get[Boolean]( "married" ) // isMarried == Some(true)
val hasChildren = config.get[Boolean]( "children" ) // hasChildren == NoneAfter the key, the user can provide a default value. The apply method will then directly return the value if defined, or else the default value passed as argument.
val isMarried = config( "married", false ) // isMarried == true
val hasChildren = config( "children", false ) // hasChildren == falseThe type will be inferred from the default value, so you can spare the type annotation.
When accessing a value, the conversion is realized by an implicit
ValueConverter. They are already defined for most basic types in
the configrity package object. See ValueConversions
to learn how to write converters for other types.
A Configuration can be modified using the set method. It either creates
a new value or replace silently an existing one. Since Configuration is
immutable, a new instance will be returned:
val config2 = config.set("name","Robert").set("children",true)
val name = config2[String]( "name" ) // name == "Robert"
val hasChildren = config2[Boolean]( "children" ) // hasChildren == trueThe method clear allows to remove an existing key. If the key does not exist,
nothing will happen:
val config2 = config.clear( "name" ).clear( "address" )
val name = config2.get[String]( "name" ) // name == None