math - Kotlin, generic addition -
is possible implement generic, let's say, addition 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 + return res } }
because here compilers complains a.x + bx
, a.y + by
:
type mismatch. required: t found: numberex
one way employ recursive numberex
definition so:
interface numberex<t : numberex<t>> { operator fun plus(other: t): t }
this require implementation provide plus operator:
class anumber : numberex<anumber> { override fun plus(other: anumber): anumber { //todo } }
and make type safe , understandable compiler use in vec2t
interface vec2t<t : numberex<t>> { ... }
Comments
Post a Comment