Simple Generic Function in Kotlin Fails

孤人 提交于 2020-04-30 10:05:10

问题


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:


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.



来源:https://stackoverflow.com/questions/56554959/simple-generic-function-in-kotlin-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!