注意:这个问题不是关于泛型类,而是关于泛型函数。 (我不认为它是这个的重复:它比这更具体。
在我们的项目中,我们有一些实用程序函数来扩展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>
如果有任何语言可以震撼这一点,那么 Kotlin 肯定可以!思潮?
可以使用 fun <T> T.toFixed(...)
来实现泛型类型的扩展。这样做,this
是可访问的。
那么问题是,扩展可以用于任何类型!您可以使用T
上限来限制它:
fun <T: Number> T.toFixed(...)
如果您确实必须将扩展限制为仅Float
和双精度,则有必要仅扩展具体类型。另外看看 Koltin math
图书馆,可能会有所帮助:)(适用于 1.2 测试版):
https://github.com/JetBrains/kotlin/blob/1.2-Beta/js/js.libraries/src/core/math.kt