Move a big part of the getValue method body to a new function called convertValue, to avoid code duplication

This commit is contained in:
Username404 2021-10-27 18:18:07 +02:00
parent 7573114c6a
commit 74df5b8639
Signed by: Username404-59
GPG Key ID: 7AB361FBB257A5D1
1 changed files with 22 additions and 14 deletions

View File

@ -28,6 +28,8 @@ import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import org.jetbrains.annotations.ApiStatus
import kotlin.reflect.KClass
import kotlin.reflect.full.isSuperclassOf import kotlin.reflect.full.isSuperclassOf
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
@ -133,27 +135,33 @@ object Configuration {
} }
operator fun invoke() = obtained operator fun invoke() = obtained
inline operator fun <reified T> 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 <T: Any> convertValue(type: KClass<T>): 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 <reified T: Any> getValue(ref: Any?, property: KProperty<*>): T =
@Suppress("DEPRECATION_ERROR") @Suppress("DEPRECATION_ERROR")
if (ModifiableValues.containsKey(property.name)) if (ModifiableValues.containsKey(property.name))
ModifiableValues[property.name] as T ModifiableValues[property.name] as T
else try { else try {
invoke().getValue(ref, property) invoke().getValue(ref, property)
} catch (e: ConfigException) { } catch (e: ConfigException) {
when { convertValue(T::class) ?: throw e
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
}
} }
operator fun <T> setValue(ref: Any?, property: KProperty<*>, value: T) = @Suppress("DEPRECATION_ERROR") operator fun <T> setValue(ref: Any?, property: KProperty<*>, value: T) = @Suppress("DEPRECATION_ERROR")
ModifiableValues.setValue(ref, property, value) ModifiableValues.setValue(ref, property, value)
} }