elect
elect

Reputation: 7180

Kotlin, generic addition

Is it possible to implement a generic, let's say, addition like the following:

public abstract interface NumberEx {

    abstract fun plus(other: NumberEx): NumberEx
}

abstract interface Vec2t<T : NumberEx> {

    open var x: T
    open var y: T

    fun add(res: Vec2t<T>, a: Vec2t<T>, bX: T, bY: T): Vec2t<T> {
        res.x = a.x + bX
        res.y = a.y + bY
        return res
    }
}

Because here the compilers complains about a.x + bX and a.y + bY:

Type mismatch. Required: T Found: NumberEx

Upvotes: 3

Views: 564

Answers (1)

miensol
miensol

Reputation: 41678

One way is to employ a recursive NumberEx definition like so:

interface NumberEx<T : NumberEx<T>> {
    operator fun plus(other: T): T
}

This would require an implementation to provide a plus operator:

class ANumber : NumberEx<ANumber> {
    override fun plus(other: ANumber): ANumber {
        //TODO
    }
}

And would make it type safe and understandable by compiler to use in Vec2t

interface Vec2t<T : NumberEx<T>> {
  ...
}

Upvotes: 6

Related Questions