Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
pureconfig ConfigReader for case class with "auxiliary constructor" type logic
case class HalfLife(lowerBoundHours: BigDecimal, upperBoundHours: BigDecimal, meanHours: BigDecimal)
def computeMean(lowerBoundHours: BigDecimal, upperBoundHours: BigDecimal): BigDecimal = {
// TODO linear interpolation is terrible here. These are exponential quantities.
(lowerBoundHours + upperBoundHours) / 2
// Hack to get pureconfig to create instances of HalfLife without an explicit mean-hours value.
import com.typesafe.config.{ConfigObject, ConfigValueFactory}
import pureconfig.ConfigReader
implicit val readerWithDefault = ConfigReader[HalfLife].contramapConfig {
case co: ConfigObject =>
if (co.containsKey("mean-hours")) co
else {
val lowerBoundHours = ConfigReader[BigDecimal].from(co.toConfig.getValue("lower-bound-hours")).right.get
val upperBoundHours = ConfigReader[BigDecimal].from(co.toConfig.getValue("upper-bound-hours")).right.get
val meanHours = computeMean(lowerBoundHours, upperBoundHours)
co.withValue("mean-hours", ConfigValueFactory.fromAnyRef(meanHours))
Copy link

briangordon commented Sep 11, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment