在 Kotlin 中重载等于 BigDecimal
Overload equals of BigDecimal in Kotlin
在 Kotlin 文件中,我尝试重载 BigDecimal class 的 equals 方法。我有以下代码:
fun BigDecimal.equals(n: Any?): Boolean = n is Int && this.compareTo(BigDecimal(n)) == 0
问题是这个函数不会被 n.equals(1) 调用,其中 n 是 BigDecimal 类型.
有什么问题,我该如何解决?
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.
您不能 覆盖 或 类 的影子函数与扩展函数。查看一个非常相似的问题的答案 here。
使用中缀扩展函数,如 a eq b
/ a notEq b
:
internal infix fun BigDecimal.eq(other: BigDecimal): Boolean = this.compareTo(other) == 0
internal infix fun BigDecimal.eq(other: Int): Boolean = this.compareTo(other.toBigDecimal()) == 0
internal infix fun BigDecimal.notEq(other: BigDecimal): Boolean = !(this eq other)
internal infix fun BigDecimal.notEq(other: Int): Boolean = !(this eq other)
在 Kotlin 文件中,我尝试重载 BigDecimal class 的 equals 方法。我有以下代码:
fun BigDecimal.equals(n: Any?): Boolean = n is Int && this.compareTo(BigDecimal(n)) == 0
问题是这个函数不会被 n.equals(1) 调用,其中 n 是 BigDecimal 类型. 有什么问题,我该如何解决?
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.
您不能 覆盖 或 类 的影子函数与扩展函数。查看一个非常相似的问题的答案 here。
使用中缀扩展函数,如 a eq b
/ a notEq b
:
internal infix fun BigDecimal.eq(other: BigDecimal): Boolean = this.compareTo(other) == 0
internal infix fun BigDecimal.eq(other: Int): Boolean = this.compareTo(other.toBigDecimal()) == 0
internal infix fun BigDecimal.notEq(other: BigDecimal): Boolean = !(this eq other)
internal infix fun BigDecimal.notEq(other: Int): Boolean = !(this eq other)