Kotlin扩展功能-覆盖现有方法

Pse*_*328 0 kotlin kotlin-extension

是否可以做类似的事情:

/**
 * 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() ?: ""
Run Code Online (Sandbox Code Playgroud)
  • 这会怎么办?这将使toUpperCasenull安全。
  • 我有什么问题?返回值this?.toUpperCase()表示扩展功能

是重命名扩展功能的唯一选择,还是可以从其中引用“超级”功能?

Fox*_*igh 6

作为pau1adam其实只是列举说,成员胜出当一个成员是适用的。这意味着toUpperCase()为可空类型定义扩展函数String?是完全有效的。

  • 调用toUpperCase()非 null 时String,将调用成员函数。
  • 调用toUpperCase()nullable 时String?,没有成员函数。因此调用扩展函数。

安全调用运算符?.实际上自动this转换为非空String类型,因此您定义的函数完全符合您的要求。

您可以在源中找到更多详细信息,其中解释了如何Any?.toString()实现。


pau*_*dam 5

您不能覆盖现有的成员函数。

如果类具有成员函数,并且定义的扩展函数具有相同的接收者类型,则相同的名称适用于给定的参数,则该成员总是获胜。

资源

是重命名扩展功能的唯一选择,还是可以从其中引用“超级”功能?

您将必须重命名扩展函数并从内部调用要使用的成员函数。