注意:这个问题不是泛型类,而是泛型函数。(我不相信这是this one重复:它是比这更具体)Kotlin在Float和Double之间共享扩展函数的实现
在我们的项目,我们的效用函数少数延长Double
和Float
,如toFixed
(灵感Javascript's Number.toFixed
)
fun Double.toFixed(digits: Int):String = java.lang.String.format("%.${digits}f", this)
fun Float.toFixed(digits: Int):String = java.lang.String.format("%.${digits}f", this)
正如你所看到的,Double.toFixed
和Float.toFixed
具有相同的实现。
因为还有其他几个更复杂的扩展函数,所以在一个版本(例如Double.toPrecision
)中的改进和错误修复必须手动保持同步(与Float.toPrecision
),这是无聊和容易出错的。
我尝试将重复的实现移动到共享的<templated>
函数中,但是(正确)它在未绑定函数的上下文中不能访问this
。
为了说明,我希望这样的事情:
private fun <T>toFixed(digits: Int):String = java.lang.String.format("%.${digits}f", this)
fun Double.toFixed = ::toFixed<Double>
fun Float.toFixed = ::toFixed<Float>
如果任何语言可以摇滚这个,肯定科特林可以!思考?
的[泛型类在科特林扩展功能(可能的复制https://stackoverflow.com/questions/32883936 /扩展函数换通用类合科特林) –