What to do for overriding the PureConfig behavior in Scala ?

PureConfig has its own predefined behavior for reading and writing to the configuration files, but sometimes we got the tricky requirement in which we need some specific behavior; for example to read the config.

It is possible to override the behavior of PureConfig for a certain type by implementing another instance of ConfigReader, ConfigWriter or ConfigConvert. So in this blog we will discuss all 3 override types.

1. ConfigReader:
The default behavior of PureConfig for String is to return the string itself in the configuration.
For example, when below configuration will be read by PureConfig, it will be read as it is :
application.conf:

Reading configuration:

Output :

This is the default behavior of ConfigReader in which the output is same as it is defined in configuration file.

Now let’s try to override the above behavior. Now we want that Strings are always read upper case. For this, we need to define custom ConfigReader instance for String:

After adding above line, lets take a look on output :

View full code on github.

2. ConfigWriter:

Add below line to override the String write behavior:

Write config:

output:

You can see above that “!!!” has been appended to the each string value.

View full code on github

3. ConfigConvert:

If you want to define both operations, the easier way to add full support for a class is by creating a ConfigConvert:

A ConfigConvert is both an instance of ConfigReader and an instance of ConfigWriter, so it can be used everywhere one of them is required.

View full code on github

That’s it. Hope you enjoy the reading.

Happy Blogging !!!

Happy Coding !!!


KNOLDUS-advt-sticker

Written by 

Rishi is a Lead Consultant, with experience of more than 7 years. Rishi is product focused developer who loves developing both front-end user interfaces and scalable back-end infrastructure. He is a good team player, quick learner and a humble person. He has good time management skills, aimed to give best results and fully dedicated towards his work & responsibilities. He is able to work as individual and as well as in team. He loves to share his knowledge, therefore he often writes technical blogs.

1 thought on “What to do for overriding the PureConfig behavior in Scala ?

Leave a Reply

%d bloggers like this: