kotlin - 如何(强制)在 Kotlin 中重载整数的加号?

标签 kotlin operator-overloading addition

我想让 plus 有别的意思,而不是加法。例如,为计算图创建惰性表达式。不幸的是,类扩展不能覆盖成员函数。以下代码将打印 3:

operator fun Int.plus(other: Int) = listOf(this, other)

fun main() {
    println( 1 + 2 )
}

是否可以强制覆盖?

最佳答案

不,这是不可能的。 1 + 2 被降低为 1.plus(2),编译器如何找到合适的 plus 方法有明确定义的顺序. Specification:

If a call is correct, for a callable f with an explicit receiver e of type T the following sets are analyzed (in the given order):

  1. Non-extension member callables named f of type T;
  2. Extension callables named f, whose receiver type U conforms to type T, in the current scope and its upwards-linked scopes, ordered by the size of the scope (smallest first), excluding the package scope;
  3. [...]

[...]

When analyzing these sets, the first set which contains any applicable callable is picked for c-level partition, which gives us the resulting overload candidate set.

因此总是首先找到Int 中声明的plus 方法,然后搜索就此停止。您定义的任何扩展都将被忽略。

假设如果内置的Int.plus 是一个隐式导入的扩展函数,那么您的代码就可以工作!隐式导入的扩展在该列表中排名第 6 :)

对于这种情况,我的解决方法是使用“通过添加反引号来声明具有几乎任何名称的函数”功能:

infix fun Int.`+`(other: Int) = listOf(this, other)

fun main() {
    println( 1 `+` 2 )
}

这不适用于某些具有保留字符的名称,例如方括号、尖括号、斜杠和点(并非详尽列表)。

关于kotlin - 如何(强制)在 Kotlin 中重载整数的加号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71588021/

相关文章:

android - RxJava2 定时器和 combineLatest

kotlin - 返回菊花链伴随对象的实例

java - Baseadapter缓慢且滚动滞后

c++ - 重载 + 运算符以组合两个使用 vector 的字典

c++ - 左值需要作为运算符重载赋值的左操作数

Java 将值添加到现有值(int)

api - 如何通过API在OpenStreetMap上添加点?

java - Azure 函数的 CosmosDBInput 绑定(bind)未使用 HttpTrigger 中定义的路径变量

c++ - 同时处理基类的多个指针时如何处理多态性?

c - 添加与 ORing 性能