In java if I want to intercept the method calls on a class I can use Proxy.newProxyInstance()
and provide an InvocationHandler
implementing invoke()
.
I've seen that in kotlin you can use delegated properties to kind of intercept property access.
Is there any feature of kotlin that could be used to provide similar functionality for methods?
Kotlin does not have a standard and unified way to create Proxies
. You can still use Proxy.newProxyInstance()
when using the K/JVM platform, but keep in mind the Kotlin compiler will generate/rename method (you can use @JvmName
to kind of control that). On the JS platform there is a somewhat similar feature (MDN doc here), and you have @JsName
to handle method renaming.
As for Native there is (to my knowledge) no way of doing it as reflection is not implemented.
The goal of delegation is not to provide an alternatives to proxy, but you might get away with them for some use cases.
There is a feature request for this feature here, but it did not received much attention