Last active
September 11, 2017 00:59
-
-
Save briangordon/df79f7cd3750ac9fe1109553c8262aee to your computer and use it in GitHub Desktop.
pureconfig ConfigReader for case class with "auxiliary constructor" type logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pureconfig/pureconfig#308