Skip to content

Instantly share code, notes, and snippets.

@NyCodeGHG
Last active March 18, 2021 13:43
Show Gist options
  • Save NyCodeGHG/52e99f968b3cda9360774f393cbd4620 to your computer and use it in GitHub Desktop.
Save NyCodeGHG/52e99f968b3cda9360774f393cbd4620 to your computer and use it in GitHub Desktop.
Spigot Configuration Boilerplate for Kotlin
package de.nycode.fynixlobby.config
import de.nycode.fynixlobby.PluginInstance
import de.nycode.fynixlobby.config.feature.LobbyWeatherType
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
typealias ChangeListener<T> = (newValue: T) -> Unit
fun config(path: String, default: String): ConfigurationProperty<String> =
ConfigurationProperty(path, { it }, default)
fun <T> config(path: String, default: T, transform: (String) -> T): ConfigurationProperty<T> =
ConfigurationProperty(path, transform, default)
class ConfigurationProperty<T>(
private val configPath: String,
private val transform: (String) -> T?,
private val default: T,
private var onChange: ChangeListener<T> = { _ -> }
) : ReadWriteProperty<Any, T> {
fun onChange(listener: ChangeListener<T>): ConfigurationProperty<T> {
onChange = listener
return this
}
init {
if (PluginInstance.config.get(configPath) == null) {
PluginInstance.config.set(configPath, default)
PluginInstance.saveDefaultConfig()
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
PluginInstance.config.set(configPath, value)
onChange(value)
}
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return transform(PluginInstance.config.getString(configPath) ?: return default) ?: default
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment