Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Extension Functions - Override existing method

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() ?: ""
  • What would this do? It would make toUpperCase null safe.
  • What problem am I having? the return value, this?.toUpperCase(), refers to the extension function

Is the only option to rename my extension function or is there a way to refer to the "super" function from within it?

like image 734
Psest328 Avatar asked Oct 02 '18 13:10

Psest328


2 Answers

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.

like image 139
pau1adam Avatar answered Oct 16 '22 14:10

pau1adam


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-null String, the member function is called.
  • When calling 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.

like image 41
Fox Sleigh Avatar answered Oct 16 '22 14:10

Fox Sleigh