Skip to content

Instantly share code, notes, and snippets.

@briangordon
Last active September 11, 2017 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briangordon/df79f7cd3750ac9fe1109553c8262aee to your computer and use it in GitHub Desktop.
Save briangordon/df79f7cd3750ac9fe1109553c8262aee to your computer and use it in GitHub Desktop.
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))
}
}
@briangordon
Copy link
Author

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