Kotlin:当扩展函数隐藏 class 默认实现时?
Kotlin: When extension function hides the class default implementation?
我想知道当覆盖现有的 class 函数时,具有相同签名的扩展函数会生效吗?
这是我的示例代码:
fun String.toUpperCase(): String = "ext. function impl."
fun main(args: Array<String>) {
println("Hello".toUpperCase()) // ext. function impl.
println(MyClass().toUpperCase()) // class impl.
}
class MyClass {
fun toUpperCase() : String {
return "class impl."
}
}
fun MyClass.toUpperCase() : String {
return "ext. function impl."
}
所以:
- 规则是什么?每个人什么时候被调用?
- 我怎样才能推翻这个决定?可能吗?
来自the Kotlin docs(强调不是我的):
If a class has a member function, and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.
您的字符串示例之所以有效,是因为库提供的 String.toUpperCase()
已经是 扩展函数,而不是成员函数。文档没有说明这里发生了什么,但假设本地扩展获胜似乎是合理的。
我不认为有任何方法可以改变这种行为。这可能是最好的,因为在许多情况下它会违反最小惊讶原则(即难以理解的行为)。
我想知道当覆盖现有的 class 函数时,具有相同签名的扩展函数会生效吗?
这是我的示例代码:
fun String.toUpperCase(): String = "ext. function impl."
fun main(args: Array<String>) {
println("Hello".toUpperCase()) // ext. function impl.
println(MyClass().toUpperCase()) // class impl.
}
class MyClass {
fun toUpperCase() : String {
return "class impl."
}
}
fun MyClass.toUpperCase() : String {
return "ext. function impl."
}
所以:
- 规则是什么?每个人什么时候被调用?
- 我怎样才能推翻这个决定?可能吗?
来自the Kotlin docs(强调不是我的):
If a class has a member function, and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.
您的字符串示例之所以有效,是因为库提供的 String.toUpperCase()
已经是 扩展函数,而不是成员函数。文档没有说明这里发生了什么,但假设本地扩展获胜似乎是合理的。
我不认为有任何方法可以改变这种行为。这可能是最好的,因为在许多情况下它会违反最小惊讶原则(即难以理解的行为)。