concept property file in category kotlin

This is an excerpt from Manning's book The Joy of Kotlin.
Most software applications are configured using property files that are read at startup. Properties are key/value pairs, and both keys and values are written as strings. Whatever the chosen property format (key =value, XML, JSON, YAML, and so on), the programmer always has to read strings and transform them into objects. This process is tedious and error-prone.
You can use a specialized library for reading property files, but if something goes wrong, you’ll find yourself throwing exceptions. To get more functional behavior, you’ll have to write your own library. This library lets you
14.3.1 Loading the property file
Whichever format you use, the process is exactly the same: reading the file and handling any exception that could arise in that process. The first thing to do is read the property file and return a
Result<Properties>, as shown in the next listing.Listing 14.2 Reading a property file
class PropertyReader(configFileName: String) { internal val properties: Result<Properties> = #1 Result.of { #2 MethodHandles.lookup().lookupClass() #3 .getResourceAsStream(configFileName) #4 .use { inputStream -> #5 Properties().let { it.load(inputStream) #6 it #7 } } } } fun main(args: Array<String>) { val propertyReader = PropertyReader("/config.properties") #8 propertyReader.properties.forEach(onSuccess = { println(it) }, onFailure = { println(it) }) } #1 The PropertyReader class holds a Result<Properties> from which you might read property values. #2 The Result.of function will return a Success if all goes well or a Failure if an exception occurs. #3 This allows to get a reference to the generated class although the function is placed at package level. #4 Loads the file from the classpath #5 Loads the property file, possibly causing an IOException. #6 Loads the properties from the InputStream #7 The last line of the block returns the value. You need to specify the value using the default parameter name “it” because the previous line returns a Boolean. #8 Here, the file is placed at the root of the classpath.