Home > Blockchain >  How to define function, which accepts all numerics in Kotlin
How to define function, which accepts all numerics in Kotlin

Time:02-22

What I thought didn't work

fun compute1(x: Double, y:Double) : Double {
    return x   y
}

fun compute2(x: Number, y:Number) : Number {
    return x   y // can't use plus
}

fun main() {
    compute1(12, 13) // cant use integers
}

How to accomplish?


Solution should be as laconic as in java

public class MathEx {
   public static double compute(double x, double y) {
      return x y;
   }
}

CodePudding user response:

You could overload the function to receive the combinations that you want

fun compute(x:Double, y:Double) = x   y
fun compute(x:Float, y:Float) = x   y
fun compute(x:Int, y:Int) = x   y
fun compute(x:Double, y:Int) = x   y
fun compute(x:Float, y:Int) = x   y

fun main() {
    compute(12, 13)
}

Quite verbose, or you can define just one or two and convert the number before calling the function, which is not very efficient but it would work

fun compute(x:Double, y:Double) = x   y

fun main() {
    compute(12.toDouble(), 13.toDouble())
}

from https://kotlinlang.org/docs/basic-types.html#floating-point-types

Note that unlike some other languages, there are no implicit widening conversions for numbers in Kotlin. For example, a function with a Double parameter can be called only on Double values, but not Float, Int, or other numeric values.

CodePudding user response:

It's not a perfect solution since there are examples where you get rounding errors but for your use case this might be good enough

fun compute2(x: Number, y:Number) : Double{
    return x.toDouble()   y.toDouble()
}
  • Related