But what happens if the instance was created within Javascript and I try to cast it to my implementation within Kotlin?
➕ 1
g
gbaldeck
10/16/2018, 2:18 AM
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
fkrauthan
10/16/2018, 2:29 AM
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
gbaldeck
10/16/2018, 2:32 AM
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
gbaldeck
10/16/2018, 2:33 AM
actually, having re-read it, you are describing the delegation pattern, what you want is at that link
f
fkrauthan
10/16/2018, 2:34 AM
Oh cool I totally missed that kotlin has a native feature for that thanks 🙂