Home > Back-end >  How can I add two values with numeric type in function with kotlin?
How can I add two values with numeric type in function with kotlin?

Time:01-07

i wanna sum 2 Int or 2 Double with using Generic.

fun <T> someFunction(a: T,b: T) {
    Log.d(TAG, "${a b}") 
}

CodePudding user response:

I think this might work for you

fun <T: Number> someFunction(a: T,b: T) {
    val result =  (a.toDouble() b.toDouble()) as T
    Log.d(TAG, "$result")
}

or if you want to return it

fun <T: Number> someFunction(a: T,b: T): T {
    return (a.toDouble() b.toDouble()) as T
}

CodePudding user response:

inline fun <reified T : Number> someFunction(a: T, b: T): T? {
  return when {
    a is Int && b is Int       -> (a.toInt()   b.toInt()) as T
    a is Double && b is Double -> (a.toDouble()   b.toDouble()) as T
    else                       -> null
  }
}

val resultInt = someFunction(2, 3)           // value: 5   , type: Int?
val resultDouble = someFunction(2.25, 3.5)   // value: 5.75, type: Double?
val resultMixed = someFunction(2, 3.5)       // value: null, type: Number?
  •  Tags:  
  • Related