I know I could use extension functions. But If I n...
# javascript
f
I know I could use extension functions. But If I need to extensively extend a existing javascript class monkey patching should be easier to use
f
But what happens if the instance was created within Javascript and I try to cast it to my implementation within Kotlin?
1
g
if thats the case I would import it and define an external interface for it rather than an external class. When you do the import make sure to define its type as the external interface. As long as you place the same properties and functions on the external interface that exist on the object then it will work
f
But the idea of monkey patching is to have the same methods + additional methods and variables. So commonly you would do something like this in the JS world
const myClassInstance = new MyClass(baseClassInstance);
and the constructor of
MyClass
would store the reference to the base instance and pass through all methods that baseclass has to the my class instance. The nice thing about JS in this case is it can be a simple array of properties that you want to pass through. E.g.
this.myMethod = baseInstance.myMethod;
g
If you are not instantiating the class inside kotlin, which you said you arent, then you are not going to be able to extend it like that. The best way to do it would be with a class delegate https://kotlinlang.org/docs/reference/delegation.html
actually, having re-read it, you are describing the delegation pattern, what you want is at that link
f
Oh cool I totally missed that kotlin has a native feature for that thanks 🙂