Kotlin中的简单泛型函数失败 [英] Simple Generic Function in Kotlin Fails
问题描述
这是Kotlin中一个简单的泛型函数:
Here's a simple generic function in Kotlin:
fun <T> twice(x: T) : T { return 2 * x }
尝试在项目或REPL中进行构建会导致以下错误:
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 }
^
如果将return语句的操作数切换为x * 2,则错误消息将变为:
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 }
^
我在这里想念什么?
推荐答案
由于T
可能是任何东西,因此编译器无法找到匹配的times
运算符.正如您在错误消息中看到的那样,对于Int
,有多种可用的替代方法
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
但是不幸的是,没有通用的times
函数,例如Number
.恐怕在这种情况下,您必须为每个要处理的类型(例如Double
,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.
这篇关于Kotlin中的简单泛型函数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!