From 74df5b86399ad7db69778bd1c4b04bd453446e11 Mon Sep 17 00:00:00 2001 From: Username404 Date: Wed, 27 Oct 2021 18:18:07 +0200 Subject: [PATCH] Move a big part of the getValue method body to a new function called convertValue, to avoid code duplication --- .../snowygui/config/Configuration.kt | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/common/src/main/kotlin/fr/username404/snowygui/config/Configuration.kt b/common/src/main/kotlin/fr/username404/snowygui/config/Configuration.kt index f53d75d..d7163b2 100644 --- a/common/src/main/kotlin/fr/username404/snowygui/config/Configuration.kt +++ b/common/src/main/kotlin/fr/username404/snowygui/config/Configuration.kt @@ -28,6 +28,8 @@ import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json +import org.jetbrains.annotations.ApiStatus +import kotlin.reflect.KClass import kotlin.reflect.full.isSuperclassOf @OptIn(ExperimentalSerializationApi::class) @@ -133,27 +135,33 @@ object Configuration { } operator fun invoke() = obtained - inline operator fun getValue(ref: Any?, property: KProperty<*>): T = + @JvmSynthetic + @ApiStatus.Internal + @Suppress("DeprecatedCallableAddReplaceWith") + @Deprecated("This method should only be used in the getValue operator of the Configuration object", level = DeprecationLevel.ERROR) + fun convertValue(type: KClass): T? = + @Suppress("UNCHECKED_CAST") + when { + Number::class.isSuperclassOf(type) -> when (type) { + Double::class -> 2.0 + Int::class, UInt::class, + Short::class, UShort::class, + Long::class, ULong::class -> 2 + Float::class -> 2F + else -> null + } as T + type == Boolean::class -> false as T + else -> null + } + inline operator fun getValue(ref: Any?, property: KProperty<*>): T = @Suppress("DEPRECATION_ERROR") if (ModifiableValues.containsKey(property.name)) ModifiableValues[property.name] as T else try { invoke().getValue(ref, property) } catch (e: ConfigException) { - when { - Number::class.isSuperclassOf(T::class) -> when (T::class) { - Double::class -> 2.0 - Int::class, UInt::class, - Short::class, UShort::class, - Long::class, ULong::class -> 2 - Float::class -> 2F - else -> throw e - } as T - T::class == Boolean::class -> false as T - else -> throw e - } + convertValue(T::class) ?: throw e } - operator fun setValue(ref: Any?, property: KProperty<*>, value: T) = @Suppress("DEPRECATION_ERROR") ModifiableValues.setValue(ref, property, value) }