首页 > 解决方案 > kotlin 中两种泛型类型的总和

问题描述

如何在 Kotlin 中使用泛型添加两个不同类型的数量?以下是我不成功的尝试。

fun <T, U>add(a: T, b: U): Any?{
    return a.plus(b)
}

operator fun <U> U.plus(b: U) {}

fun main(){
    println(add<Int, Double>(4, 5.6))
}

我在Kotlin中搜索了“加号”运算符,当加号运算符重载时,似乎没有函数体。

/** Adds the other value to this value. */
public operator fun plus(other: Byte): Int
/** Adds the other value to this value. */
public operator fun plus(other: Short): Int
/** Adds the other value to this value. */
public operator fun plus(other: Int): Int
/** Adds the other value to this value. */
public operator fun plus(other: Long): Long
/** Adds the other value to this value. */
public operator fun plus(other: Float): Float
/** Adds the other value to this value. */
public operator fun plus(other: Double): Double

标签: kotlingenerics

解决方案


推荐阅读