Kotlin: is it possible to have a constant property dependent on an implementation generic type? -
i have following abstrac base class
abstract class vec2t<t : number>(open var x: t, open var y: t) { companion object { val size = 2 * when (/** t instance type */) { byte, ubyte -> 1 short, ushort -> 2 int, uint, float -> 4 long, ulong, double -> 8 else -> throw arithmeticexception("type undefined") } } }
that implemented, example, vec2
data class vec2(override var x: float, override var y: float) : vec2t<float>(x, y)
i wondering if possible define size
in vec2t
, call on 1 of implementation, example vec2.size
although cannot "have static fields have different values different instantiations of generic class" (as @yole commented), can define properties on each implementation , companion objects. e.g.:
abstract class vec2t<t : number> { abstract var x: t abstract var y: t abstract val size: int } class vec2f(override var x: float, override var y: float) : vec2t<float>() { companion object { const val size = 2 * 4 } override val size: int get() = size } class vec2d(override var x: double, override var y: double) : vec2t<double>() { companion object { const val size = 2 * 8 } override val size: int get() = size }
this allows reference vec2f.size
, vec2d.size
, etc. when want know size specific implementation , reference vec2t.size
when have instance (possibly of unknown implementation type) , size.
Comments
Post a Comment