classcaseabstractsealedpureconfig

Pureconfig Typesafe Config with sealed abstract case class


I am trying to incorporate Pureconfig in my use case for typesafe configurations. Been successful in mapping HOCON .conf to case class types. However, if I have to constrain my types with no side-effects on the object definition side (i.e., supress default apply() and copy()), I am using following definition approach for case class:

sealed abstract case class someConfig(name:String)

object someConfig{
    def apply(name:String):Option[someConfig]={
        if(Option(name).isDefined && name.nonEmpty){
            Some(new someConfig(name){})
        } else {
            None
        }
    }
}

To support Option[_] types, I am considering having an implicit ConfigReader. This approach seems to work, with a bit more for me to address config-keys to object mapping and instantiation.

Examples that I have searched upon so far doesn't seem to resonate this need. However, do see use of Option[_] on the object members. Tried to walk through the code samples in Pureconfig git repo.

Could someone suggest an approach where Option[T] could be supported, where T is a composite custom type? And I don't have to deal with member variable name to config key mapping, etc. i.e., avoid necessary boilerplate!


Solution

  • Because you've hidden the constructor for your class in order to channel validation through the apply, you'll have to manually construct a ConfigReader. I believe that's about as simple as putting this in your companion object:

    implicit val configReader = 
      pureconfig.ConfigReader.fromNonEmptyStringOpt[someConfig](apply)
    

    Alternatively, you could name the class implementing your abstract type in which case PureConfig's automatic derivation for sealed families would magically create the ConfigReader for you.