Kotlin 扩展函数 - 覆盖现有方法
Kotlin Extension Functions - Override existing method
是否可以这样做:
/**
* 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 安全。
- 我遇到了什么问题? return 值,
this?.toUpperCase()
,
引用扩展函数
是重命名我的扩展函数的唯一选项,还是有办法从其中引用 "super" 函数?
您不能覆盖现有的成员函数。
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?
您必须重命名您的扩展函数并从内部调用您要使用的成员函数。
source as pau1adam 引用实际上只说当成员适用时成员胜出。这意味着为可空类型 String?
定义扩展函数 toUpperCase()
是完全有效的。
- 在 non-null
String
上调用 toUpperCase()
时,将调用成员函数。
- 在可空
String?
上调用 toUpperCase()
时,没有成员函数。这样就调用了扩展函数。
安全调用运算符 ?.
实际上会自动将 this
自动转换为 non-null String
类型,因此您定义的函数完全符合您的要求。
您可以在 source 中找到更多详细信息,其中解释了如何实施 Any?.toString()
。
是否可以这样做:
/**
* 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 安全。 - 我遇到了什么问题? return 值,
this?.toUpperCase()
, 引用扩展函数
是重命名我的扩展函数的唯一选项,还是有办法从其中引用 "super" 函数?
您不能覆盖现有的成员函数。
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?
您必须重命名您的扩展函数并从内部调用您要使用的成员函数。
source as pau1adam 引用实际上只说当成员适用时成员胜出。这意味着为可空类型 String?
定义扩展函数 toUpperCase()
是完全有效的。
- 在 non-null
String
上调用toUpperCase()
时,将调用成员函数。 - 在可空
String?
上调用toUpperCase()
时,没有成员函数。这样就调用了扩展函数。
安全调用运算符 ?.
实际上会自动将 this
自动转换为 non-null String
类型,因此您定义的函数完全符合您的要求。
您可以在 source 中找到更多详细信息,其中解释了如何实施 Any?.toString()
。