https://kotlinlang.org logo
Title
g

galex

12/03/2019, 10:54 AM
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

Milan Hruban

12/03/2019, 10:57 AM
I don't think you can override extension functions
a

adimit

12/03/2019, 11:01 AM
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

galex

12/03/2019, 11:08 AM
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

gian

12/03/2019, 11:10 AM
stdlib is imported by default, isn’t it?
k

Kroppeb

12/03/2019, 11:28 AM
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

galex

12/03/2019, 11:55 AM
Yup that’s what we ended doing, renamed it