1

I make a simple function sqr, but it's not working, what's wrong ?

fun <T : Number> sqr(value: T): T {    
    return value * value
}

fun main() {
    print("${sqr(5)}")    
}
0

3 Answers 3

1

Number is an abstraction over Double, Int etc. but it doesn't include any common behavior. Rather, it contains functionality for converting between the different concrete types.

See the source here (or press "Go to implementation" in the IDE)

You'd have to convert them to a concrete subclass in order to get it to compile:

fun <T : Number> sqr(value: T): T {    
    return value.toInt() * value.toInt()
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is no times function (which the * operator is translated to) for Number.

Number is just the abstract super class of Int, Float, Double etc. and only contains abstract conversion functions: toInt(), toFloat(), toDouble() etc.

So, how to get around that and have a sqrt function for all of them?

Since there is no super type for them which includes the basic operations, the best idea would be most likely to just have a separate implementation for each type and not use generic types.

fun sqr(value: Int) = value * value
fun sqr(value: Float) = value * value
fun sqr(value: Double) = value * value
// ...

Comments

1

Alternatively, you could have an operator extension on Number, taking advantage of kotlin smartcasts; which could look something like this:

operator fun Number.times(value: Number): Number {
   return when(this) {
        is Int -> this * value.toInt()
        is Double -> this * value.toDouble()
        is Short -> this * value.toShort()
        is Float -> this * value.toFloat()
        else -> throw IllegalArgumentException("Value is not a number")
    }
}

So your square function would be:

fun sqr(value: Number): Number {
    return value * value
}

I suppose the benefit here is that you maintain only 1 square function, and an operator with a number of cases that represent which concrete number classes you wish to support.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.