Kotlin Extension Functions - Override existing method
Asked Answered
A

2

18

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?

Ancona answered 2/10, 2018 at 13:48 Comment(3)
Assuming there were a way to achieve this, it would be ambiguous, right? If I do "foo".toUpperCase() which method would get called?Enosis
I would assume the extension function.... but I hadn't considered that until nowAncona
What I mean is, toUpperCase is already an extension method in Kotlin.Enosis
H
21

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.

Helvetii answered 2/10, 2018 at 15:26 Comment(0)
F
11

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.

Fishing answered 11/5, 2019 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.