Kotlin, generic operation on Number

后端 未结 1 1111
太阳男子
太阳男子 2021-01-06 03:28

I have the following

abstract interface Vec2t {    
    var x: T
    var y: T
}

data class Vec2(override var x: Fl

相关标签:
1条回答
  • 2021-01-06 04:04

    Unfortunately there's no clean way to have generic abs function. You can work it around with the following abs definition:

    object glm {
        fun <T : Number> abs(x: T): T {
            val absoluteValue: Number = when (x) {
                is Double -> Math.abs(x)
                is Int -> Math.abs(x)
                is Float -> Math.abs(x)
                is BigDecimal -> x.abs()
                is BigInteger -> x.abs()
                else -> throw IllegalArgumentException("unsupported type ${x.javaClass}")
            }
            @Suppress("UNCHECKED_CAST")
            return absoluteValue as T
        }
    }
    

    Which would make it possible to use in your context:

    fun abs(res: Vec2, a: Vec2): Vec2 {
        res.x = glm.abs(a.x)
        ...
    }
    
    0 讨论(0)
提交回复
热议问题