Ok, this is annoying ``` fun test(a: Number, y:...
# getting-started
r
Ok, this is annoying
Copy code
fun test(a: Number, y: Number) {
        return a / y
    }
It errors
Copy code
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public inline operator fun BigDecimal.div(other: BigDecimal): BigDecimal defined in kotlin
public inline operator fun BigInteger.div(other: BigInteger): BigInteger defined in kotlinkotlin(UNRESOLVED_REFERENCE_WRONG_RECEIVER)
I do not want to change the function signature to
fun test(a: Double, y: Double)
I can do this internally to avoid changing the function signature
Copy code
return a as Double / y as Double
But it is cumbersome. Does the
Number
type not have any way to do division?
y
It doesn't support it because there's no way that makes sense by default to represent the result of the division. However, what you can do is convert them to big decimal first then divide, you just have to make that choice yourself.
Copy code
operator fun Number.div(other: Number): BigDecimal = BigDecimal(toString()) / BigDecimal(other.toString())
You could also convert to Double instead.
a
A long is Number, a double is a Number. What is the reslt of long / double or double / long?
r
implicitly treating both as either the upper or lower bound sounds reasonable to me.
If you do long / double, it could act as long / double as long
I tried earlier and it looks like even subtraction is not supported. You can't do a
Number - Number
a
But the compiler doesn't know what's what at compile time so it cant determine that.
Do you even like programming in kotlin, because I get the feeling you don't 😄
a
You could either create overloads for each standard number type, or just convert the number to a double/other decimal type which is what I usually do (using
x.toDouble()
, not
x as Double
as that’ll throw a CCE if the number isn’t already a double)
y
If you want something more complicated for representing operations that should work for any specified number type, then have a look at this. I came up with that encoding, so I'm happy to answer any questions!