Andrei
06/05/2018, 9:26 AMtypealias Namespace = String
sealed class RuntimeProperties(val ns: Namespace, val properties: Properties)
class FooProperties(properties: Properties) : RuntimeProperties("foo", properties) {
val url by PropertyResolver.String
val user by PropertyResolver.String
val pass by PropertyResolver.String
}
class BarProperties(properties: Properties) : RuntimeProperties("bar", properties) {
val maximum: Int by PropertyResolver(Int::class)
}
class PropertyResolver<T : Any>(x: KClass<T>) : ReadOnlyProperty<RuntimeProperties, T> {
companion object {
val String = PropertyResolver(String::class)
}
override operator fun getValue(thisRef: RuntimeProperties, property: KProperty<*>): T = with(thisRef) {
val key = "${ns}.${property.name}"
val raw = properties.getOrElse(key) {
error("$key is not set among ${properties.propertyNames()}")
}!!.toString()
val type = property.returnType.jvmErasure
return when (type) {
Int::class -> parseInt(raw)
Long::class -> parseLong(raw)
String::class -> raw
else -> error("$type cannot be handled")
} as T
}
}