作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是Kotlin中的一个简单的泛型函数:
fun <T> twice(x: T) : T { return 2 * x }
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 }
^
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
。恐怕在这种情况下,您必须为要处理的每种类型创建重载,即
Double
,
Int
等。
关于generics - Kotlin中的简单泛型函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554959/
我是一名优秀的程序员,十分优秀!