注意:這個問題不是泛型類,而是泛型函數。(我不相信這是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 /擴展函數換通用類合科特林) –