如何编写适用于所有数字的 Kotlin 函数?



这段代码不起作用

fun sum(x: Number, y: Number) = x + y
println(sum(2.2, 2))

不,它不会。加号运算符实际上是一个函数,它不是在 Number 类中声明的,而是在扩展Number的具体类中声明的。您可以在编译器错误中看到它:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public inline operator fun BigDecimal.plus(other: BigDecimal): BigDecimal defined in kotlin
@InlineOnly public inline operator fun BigInteger.plus(other: BigInteger): BigInteger defined in kotlin
public operator fun <T> Array<???>.plus(elements: Array<out ???>): Array<???> defined in kotlin.collections
public operator fun <T> Array<???>.plus(elements: Collection<???>): Array<???> defined in kotlin.collections
public operator fun <T> Array<Number>.plus(element: Number): Array<Number> defined in kotlin.collections
public operator fun BooleanArray.plus(element: Boolean): BooleanArray defined in kotlin.collections
public operator fun BooleanArray.plus(elements: BooleanArray): BooleanArray defined in kotlin.collections
public operator fun BooleanArray.plus(elements: Collection<Boolean>): BooleanArray defined in kotlin.collections
public operator fun ByteArray.plus(element: Byte): ByteArray defined in kotlin.collections
public operator fun ByteArray.plus(elements: ByteArray): ByteArray defined in kotlin.collections
...

但是这段代码将起作用:

// Don't try this at home !!!
fun sum(x: Number, y: Number) = x.toDouble() + y.toDouble()

好吧,它至少会编译。对于两个大十进制,你宁愿不会得到预期的结果。

最新更新