1

Here's a simple generic function in Kotlin:

fun <T> twice(x: T) : T { return 2 * x }

Attempting to build this (either in a project or REPL) results in the following errors:

error: none of the following functions can be called with the arguments supplied: 
public final operator fun times(other: Byte): Int defined in kotlin.Int
public final operator fun times(other: Double): Double defined in kotlin.Int
public final operator fun times(other: Float): Float defined in kotlin.Int
public final operator fun times(other: Int): Int defined in kotlin.Int
public final operator fun times(other: Long): Long defined in kotlin.Int
public final operator fun times(other: Short): Int defined in kotlin.Int
fun <T> twice(x: T) : T { return 2 * x }
                                   ^

If I switch the return statement operands to x * 2, the error messages become:

error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public inline operator fun BigDecimal.times(other: BigDecimal): BigDecimal defined in kotlin
@InlineOnly public inline operator fun BigInteger.times(other: BigInteger): BigInteger defined in kotlin
fun <T> twice(x: T) : T { return x * 2 }
                                   ^

What am I missing here?

1 Answer 1

3

Since T could be anything, the compiler is not able to find a matching times operator. As you can see in the error message, for Int, there a multiple alternatives available

public final operator fun times(other: Byte): Int defined in kotlin.Int
public final operator fun times(other: Double): Double defined in kotlin.Int
public final operator fun times(other: Float): Float defined in kotlin.Int
public final operator fun times(other: Int): Int defined in kotlin.Int
public final operator fun times(other: Long): Long defined in kotlin.Int
public final operator fun times(other: Short): Int defined in kotlin.Int

But unfortunately there's no generic times function, which can be used with e.g. Number. I'm afraid in this case, you would have to create an overload for each type you want to be handling, i.e., Double, Int, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

The equivalent template function in C++, template<class T> T twice(T x) { return 2*x; } works as one would expect. So as it currently stands, Kotlin generics cannot do math on the generic type. Interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.