Custom Delegated properties in a structure other than a Map


#1

Hello,
Is it possible to delegate properties to a class other than a Map?
The following example works perfectly for me.

class HostConfig(props: Map<String, Any?>) {
    val ip: String by props
    val port: Int by props
}
`

However when I want to delegate the props to a custom class such as:

class MyDelegate {
   
}

class OtherHostConfig(otherProps:MyDelegate) {
    val ip:String by otherProps
    val port:Int by otherProps
}

It allows me to implement getValue either for Int or String but not for both.

operator fun getValue(otherHostConfig: Any, property: KProperty<*>): Int {}

What I want to do it something like ( of course this is real hypothetic) :

fun getValue(key: String): Any? {
    if ("ip".equals(key)) {
        return "127.0.0.1"
    } else if ("port".equals(key)) {
        return 8080
    } else {
        return null
    }
}

Is it possible to implement such a custom prop delegate for multiple fields, or is this something implemented specifically for Map class?
Thanks.


#2

Can I ask in what kind of variable you want to safe this info?
The map works with a reified generic, which looks at the type where it is saved.

fun <reified T>   .... return as T

Here the t is the type of the variable where it is saved to. When this is not specified, I believe it saves it as the default type of the map.

So your function needs to be something like

operator fun <reified T> getValue(otherHostConfig: Any, property: KProperty<*>) = when(T::class) {
     is Int::class - > 80
     is String:class - > "127.0.0.1"
     else -> throw Exception()
} as T

#3

With the help of your advice
following code worked for me:

operator inline fun <reified T> getValue(otherHostConfig: Any, property: KProperty<*>) =
            when (property.name) {
                "ip" -> "127.0.0.1"
                "port" -> 8080
                else -> null
            } as T

Thank you!