Reputation: 6675
is it possible to do something like:
/**
* Converts all of the characters in the string to upper case.
*
* @param str the string to be converted to uppercase
* @return the string converted to uppercase or empty string if the input was null
*/
fun String?.toUpperCase(): String = this?.toUpperCase() ?: ""
toUpperCase
null safe.this?.toUpperCase()
,
refers to the extension functionIs the only option to rename my extension function or is there a way to refer to the "super" function from within it?
Upvotes: 18
Views: 16319
Reputation: 337
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.
toUpperCase()
on a non-null String
, the member function is called.toUpperCase()
on a nullable String?
, 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.
Upvotes: 12
Reputation: 597
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.
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.
Upvotes: 21