Search code examples
kotlingenericsinfix-notation

Kotlin infix function with generics


Try to write a simple Kotlin infix function for plus operation. What's wrong with generic type?

infix fun <T : Number> T.myPlus(that: T): T = this + that

Solution

  • As others have mentioned, there's no solutions using generics for various reasons. You have to define an extension function for each Number type (Byte, Short, Int, Long, Float, Double). E.g. for Int you could do:

    when (that) {
        is Byte, is Short, is Int, is Long -> that.toLong().plus(this)
        is Float -> that + this
        is Double -> that + this
        else -> throw Exception("Types mismatch")
    }
    

    Even doing that, in some cases you need to decide whether you want to truncate or round the result.

    val n1 = 1230000000000000000L
    val n2 = 123.7
    

    This case (n1 is a Long, n2 is a Float) could be handled like this:

    is Float -> this + that.toLong()
    

    resulting in 1230000000000000123

    or it could be handled like this:

    is Float -> this.toFloat() + that
    

    resulting in 1.23E18