Can override an extension function somehow? I gues...
# getting-started
v
Can override an extension function somehow? I guess not. ๐Ÿ˜•
๐Ÿ‘Œ 1
j
Nope, they are technically statically resolved at compile time, so polymorphism doesn't work with extensions
That's actually why we don't get iterator-less ArrayList operations from the stdlib, I believe
v
:'''-(
j
that said, if you declare twice the same extension function but for different receiver types (say one being a subtype of the other), it would resolve -statically- to the most specific type
but it won't work polymorphically, so if you have
Child : Parent
and declare
Child.foo()
and
Parent.foo()
, you will be able to call the "overriden" child function only on variables that are statically known to be of type
Child
.
Copy code
Child().foo() // calls the Child extension

val child: Parent = Child()
child.foo() // calls the Parent extension
That might be sufficient for you, but since you used the term "override", it might not be.
v
It will not. A library defines an extension function and uses it and I need it to do something different.
Didn't expect it to work actually
j
A library defines an extension function and uses it and I need it to do something different
Ah. Assuming it's a JVM lib, this compiled down to a static function in the bytecode, so unless you manipulate that lib in some way, you're out of luck
I guess it's expected that you can't do that from Kotlin, it goes with the finall-by-default philosophy. This function was not meant to be overridden, so you can't do it. It might be a bit harsh, but it prevents nasty hacks I guess
v
Nothing prevents nasty hacks if you are desparate enough. But I was after some clean way. ๐Ÿ˜„
๐Ÿ˜† 1
j
Nothing prevents nasty hacks if you are desparate enough
True in a way, but ideally the nasty hack will be so hard that it will become more viable to contribute a change to the library code (when possible of course..)
e
I wrote a bytecode transform in one of my work projects to work around a bug in a closed-source dependency (replacing a static call with my own function). setting it up is the hard part, the actual code to do so is easy
๐Ÿ˜ฎ 1
j
So you were desperate enough ๐Ÿ™‚
v
I did similar things already, but iirc I used static bytecode weaving with AspectJ or something like that. ๐Ÿ˜„