1 package kotlinx.serialization.hocon 2 3 import com.typesafe.config.Config 4 import kotlinx.serialization.ExperimentalSerializationApi 5 6 /** 7 * Decoder used by Hocon during deserialization. 8 * This interface allows to call methods from the Lightbend/config library on the [Config] object to intercept default deserialization process. 9 * 10 * Usage example (nested config serialization): 11 * ``` 12 * @Serializable 13 * data class Example( 14 * @Serializable(NestedConfigSerializer::class) 15 * val d: Config 16 * ) 17 * object NestedConfigSerializer : KSerializer<Config> { 18 * override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("package.Config", PrimitiveKind.STRING) 19 * 20 * override fun deserialize(decoder: Decoder): Config = 21 * if (decoder is HoconDecoder) decoder.decodeConfigValue { conf, path -> conf.getConfig(path) } 22 * else throw SerializationException("This class can be decoded only by Hocon format") 23 * 24 * override fun serialize(encoder: Encoder, value: Config) { 25 * if (encoder is AbstractHoconEncoder) encoder.encodeConfigValue(value.root()) 26 * else throw SerializationException("This class can be encoded only by Hocon format") 27 * } 28 * } 29 * 30 * val nestedConfig = ConfigFactory.parseString("nested { value = \"test\" }") 31 * val globalConfig = Hocon.encodeToConfig(Example(nestedConfig)) // d: { nested: { value = "test" } } 32 * val newNestedConfig = Hocon.decodeFromConfig(Example.serializer(), globalConfig) 33 * ``` 34 */ 35 @ExperimentalSerializationApi 36 sealed interface HoconDecoder { 37 38 /** 39 * Decodes the value at the current path from the input. 40 * Allows to call methods on a [Config] instance. 41 * 42 * @param E type of value 43 * @param extractValueAtPath lambda for extracting value, where conf - original config object, path - current path expression being decoded. 44 * @return result of lambda execution 45 */ decodeConfigValuenull46 fun <E> decodeConfigValue(extractValueAtPath: (conf: Config, path: String) -> E): E 47 } 48