Hello, is it possible to override forEach { } ? Wh...
# announcements
g
Hello, is it possible to override forEach { } ? When we tried, the IDE at least always redirects to the stdlib, not to the one we implemented on our class. Weird or expected behavior?
m
I don't think you can override extension functions
a
You can however just not import the extension function. Remove the
import
statement for your the stdlib
forEach
then import your own
forEach
.
Overriding extension functions makes no sense, since they're static, and not actually functions that really belong to the class they're extending. BTW, I might add: defining your own
forEach
method on, say,
List<T>
is probably a silly idea. If it does something special, at least reflect that in the name, as people would otherwise be easily confused.
g
I thought local functions have precedence on extension functions, which is why it’s weird. The use case itself makes sense, it’s on some internal class which is a collection which contains in that special case a collection itself. But yeah, I am still surprised by the fact that defining our own forEach didn’t work
@adimit I think there was no import, surprisingly. Will check that again.
g
stdlib is imported by default, isn’t it?
k
If you are "overriding" for a subclass, then it can only call the extension after your type has been (smart)casted to the subtype. Anyway you could just rename the function
forEachRecursive
, or something similar.
g
Yup that’s what we ended doing, renamed it