Created
October 29, 2019 01:44
-
-
Save alexandredantas/1d8faedc898c3b04e7889b0426e0c3e8 to your computer and use it in GitHub Desktop.
an way to get typesafe configuration through raw map
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
package config | |
trait ConfigurationKey[T] { | |
private[config] final def withConfig(rawConfig: Map[String, String]): Option[T] = read(rawConfig) | |
protected def read(cfg: Map[String, String]): Option[T] | |
} | |
abstract class ConfigurationHolder[Config[_]] { | |
protected def configMap: Map[String, String] | |
final def read[T](key: Config[T])(implicit ev: Config[T] <:< ConfigurationKey[T]): Option[T] = key.withConfig(configMap) | |
} | |
abstract class SimpleConfigurationKey[T](name: String, conversion: String => T) { | |
def read(cfg: Map[String, String]): Option[T] = Try{ | |
cfg.get(name).map(conversion) | |
}.toOption.flatten | |
} | |
object config{ | |
sealed trait ExampleConfig[T] extends ConfigurationKey[T] | |
final case object ReadSomeConfig extends SimpleConfigurationKey[Long]("config_key", _.toLong) with ExampleConfig[Long] | |
final case class ExampleHolder(rawConfig: Map[String, String]){ | |
val config: ConfigurationHolder[ExampleConfig] = new ConfigurationHolder[ExampleConfig]{ | |
override def configMap: Map[String, String] = rawConfig | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment