Psest328
Psest328

Reputation: 6675

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() ?: ""

Is 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

Answers (2)

Fox Sleigh
Fox Sleigh

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.

  • 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.

Upvotes: 12

pau1adam
pau1adam

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.

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.

Upvotes: 21

Related Questions