From 99cc49d7581d7ac46e54ded24c2129bb7a629120 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 12 Aug 2020 13:58:00 +0600 Subject: [PATCH] optionalContextual --- CHANGELOG.md | 1 + .../sdi/utils/OptionalContextualIncluding.kt | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/commonMain/kotlin/com/insanusmokrassar/sdi/utils/OptionalContextualIncluding.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fc8b83..4c47d4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ ### 0.3.1 * `Kotlin`: `1.3.71` -> `1.3.72` +* Add `SerializersModuleBuilder#optionalContextual` for more comfortable usage of `contextual` ## 0.2.0 diff --git a/src/commonMain/kotlin/com/insanusmokrassar/sdi/utils/OptionalContextualIncluding.kt b/src/commonMain/kotlin/com/insanusmokrassar/sdi/utils/OptionalContextualIncluding.kt new file mode 100644 index 0000000..085aa46 --- /dev/null +++ b/src/commonMain/kotlin/com/insanusmokrassar/sdi/utils/OptionalContextualIncluding.kt @@ -0,0 +1,21 @@ +package com.insanusmokrassar.sdi.utils + +import kotlinx.serialization.InternalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.modules.* +import kotlin.reflect.KClass + +@InternalSerializationApi +fun SerializersModuleBuilder.optionalContextual( + kClass: KClass, kSerializer: KSerializer +) = try { + contextual(kClass, kSerializer) + true +} catch (e: SerializerAlreadyRegisteredException) { + false +} + +@InternalSerializationApi +inline fun SerializersModuleBuilder.optionalContextual( + kSerializer: KSerializer +) = optionalContextual(T::class, kSerializer) \ No newline at end of file