Method and Interface delegation


#1

Hi.
We are using Kotlin for implementing realtime game servers, and we use java dynamic proxies heavily. Delegated properties in Kotlin are awesome. I would love to see a feature for delegated methods, which would allow us to implement something similar to java dynamic proxies in a statically typed way. Consider the use case:

interface RemoteService {

    fun doSomethingSwesome(param: String) : String by RemoteInvocationHandler()
}

class RemoteInvocationHandler {
    fun invoke(obj: Any, method: KCallable, params: Array<Any>) : Any? {
        //forward invocation to remote service and return result
    }
}
//alternatively, we could instantiate the entire interface by delegating it to an InvocationHandler

val service = RemoteService by RemoteInvocationHandler()

Would love to hear your thoughts on this


#2

I’m doing something similar (not gaming related) but I’m not sure what the benefit is? Behind the scenes java.lang.Proxy just writes the bytecode for the proxy class and then loads it. In your case the Kotlin compiler would do the same thing. Java’s proxies aren’t really “dynamic” - they are real objects that implement statically typed interfaces.

Would there be some concrete benefit to this, at least, on the JVM platform? I can see why you might want it if you were trying to do the same thing in JavaScript. I have mixed feelings about how far Kotlin should support the limitations of the JS platform though.


#3

Can you be more specific what exact problem is (not just the solution you require)?


#4

Hi.

@mikehearn As you rightly said, Java already provides something similar with dynamic proxies. However, there are specific scenarios in which this will not work, mostly involving platforms that do not offer runtime code generation.

@panel
I am using java dynamic proxies to build strongly typed references to services that are distributed across a network. I recently started using Kotlin. Kotlin already has delegation for properties that works in a similar way to Java dynamic proxies, at least for getter and setter functions. This feature isn’t strictly required right now, as dynamic proxies work just fine for platforms I care about at the moment, which are the server and Android. However, dynamic proxies may not be possible to implement in platforms without support for jit compilation, and those platforms will benefit from this feature.