Kotlin Extension Functions - Override existing method
The source as pau1adam cites actually only says the member wins out when a member is applicable. That means defining an extension function toUpperCase()
for the nullable type String?
is totally valid.
- When calling
toUpperCase()
on a non-nullString
, the member function is called. - When calling
toUpperCase()
on a nullableString?
, there is no member function. Thus the extension function is called.
The safe call operator ?.
actually autocasts this
to the non-null String
type, so the function you defined does exactly what you want it to.
You can find more details at the source, where they explain how Any?.toString()
could be implemented.
You cannot override an existing member function.
If a class has a member function, and an extension function is defined which has the same receiver type, the same name is applicable to given arguments, the member always wins.
source
Is the only option to rename my extension function or is there a way to refer to the "super" function from within it?
You will have to rename your extension function and call the member function you want to use from within.