How to represent a number of type either Long Or Int Or BigInteger


#1

I want to make a power function such that it can only accept Long or Int or BigInteger as argument. I tried doing it as:

fun pow(a: Number, b: Int): Number {
    if (b == 0) return 1
    if (b == 1) return a
    return when (a) {
        is Long -> {
            if (b  % 2 == 0) pow(a * a, b / 2)
            else a * pow(a * a, b / 2) as Long
        }
        is Int -> {
            if (b  % 2 == 0) pow(a * a, b / 2)
            else a * pow(a * a, b / 2) as Int
        }
        is BigInteger -> {
            if (b  % 2 == 0) pow(a * a, b / 2)
            else a * pow(a * a, b / 2) as BigInteger
        }
        else -> throw IllegalArgumentException("only Long, Int, BigInteger are supported")
    }
}

but this does not fail at compile time for decimal argument. Is there a better way to do this?


#2

Use function overloads: three distinct functions