gpt4 book ai didi

generics - Kotlin中的简单泛型函数失败

转载 作者:行者123 更新时间:2023-12-02 13:12:48 27 4
gpt4 key购买 nike

这是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 }
^

我在这里想念什么?

最佳答案

由于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。恐怕在这种情况下,您必须为要处理的每种类型创建重载,即 DoubleInt等。

关于generics - Kotlin中的简单泛型函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554959/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com