'Overload equals of BigDecimal in Kotlin
In a Kotlin file I try to overload the equals method of the BigDecimal class. I have the following piece of code for that:
fun BigDecimal.equals(n: Any?): Boolean = n is Int && this.compareTo(BigDecimal(n)) == 0
The problem is that this function does not get called by n.equals(1) where n is of type BigDecimal. What's the problem and how can I solve it?
Solution 1:[1]
You can not override or shadow functions of classes with extension functions. See the answer to a very similar question here.
Solution 2:[2]
From the documentation:
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.
Solution 3:[3]
Use infix extension functions like 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | zsmb13 |
Solution 2 | JB Nizet |
Solution 3 | WindRider |