gpt4 book ai didi

Kotlin:扩展函数何时隐藏类默认实现?

转载 作者:行者123 更新时间:2023-12-01 12:19:17 25 4
gpt4 key购买 nike

我想弄清楚什么时候覆盖现有的类函数,具有相同签名的扩展函数 - 会生效吗?

这是我的示例代码:

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() 已经 是扩展函数,而不是成员函数。文档没有说明这里发生了什么,但假设本地扩展获胜似乎是合理的。


我不认为有任何方法可以改变这种行为。这可能是最好的,因为在许多情况下它会违反最小惊讶原则(即难以理解的行为)。

关于Kotlin:扩展函数何时隐藏类默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com