通用号码加法功能

我想用Kotlin语言创建一个通用函数,该函数将添加所有类型的数字,即Double,Float,Long,Int,Byte,Char,Short。所以我创建了一个函数:

fun <T : Number> add (a: T, b: T) = a + b 

But Android Studio IDE throwing compile time error on + sign as Number class doesn't have plus method. Why is that? And can someone please provide solution for generic function in kotlin without using if else or when statement.

评论
  • mest
    mest 回复

    Your function only knows that they are both Numbers unless you check their types and cast. There is no Number.plus(Number) function so you can't add them as is. You can instead convert them to Doubles and add those, since there is a Number.toDouble() function. The type does not need to be reified.

    fun <T : Number> add (a: T, b: T) = a.toDouble() + b.toDouble()