这是Kotlin中的一个简单泛型函数:
fun <T> twice(x: T) : T { return 2 * x }
尝试在项目或REPL中进行构建会导致以下错误:
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 }
^
如果将return语句操作数切换为x * 2,则错误消息变为:
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 }
^
我在这里想念什么?
答案 0 :(得分:2)
由于T
可以是任何东西,因此编译器无法找到匹配的times
运算符。正如您在错误消息中看到的那样,对于Int
,有多种选择
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
但是不幸的是,没有通用的times
函数可以与例如Number
。恐怕在这种情况下,您将不得不为要处理的每种类型创建重载,例如Double
,Int
等。