嘗試撰寫一個簡單的 Kotlin 中綴函式進行加號操作。泛型型別有什么問題?
infix fun <T : Number> T.myPlus(that: T): T = this that
uj5u.com熱心網友回復:
正如其他人所提到的,由于各種原因,沒有使用泛型的解決方案。您必須為每種數字型別(Byte、Short、Int、Long、Float、Double)定義一個擴展函式。例如對于 Int 你可以這樣做:
when (that) {
is Byte, is Short, is Int, is Long -> that.toLong().plus(this)
is Float -> that this
is Double -> that this
else -> throw Exception("Types mismatch")
}
即使這樣做,在某些情況下,您還需要決定是要截斷還是舍入結果。
val n1 = 1230000000000000000L
val n2 = 123.7
這種情況(n1 是 Long,n2 是 Fl??oat)可以這樣處理:
is Float -> this that.toLong()
導致1230000000000000123
或者可以這樣處理:
is Float -> this.toFloat() that
導致1.23E18
uj5u.com熱心網友回復:
您忘記了operator關鍵字:
中綴運算子 fun T.plus(that: T): T = this that
編輯:
infix fun Number.infixPlus(that: Number): Number =
when (that) {
is Int -> this.toInt() that
is Long -> this.toLong() that
is Float -> this.toFloat() that
is Double -> this.toDouble() that
else -> throw Exception()
}
val n1 = 123
val n2 = 123.456
val result = n1 infixPlus n2
println("result: " result)
println("is Int: " (result is Int))
println("is Long: " (result is Long))
println("is Float: " (result is Float))
println("is Double: " (result is Double))
uj5u.com熱心網友回復:
更多的鑄造安全性:
infix fun Number.infixPlus(that: Number): Number {
return when {
this is Int && that is Int -> this that
this is Double && that is Double -> this that
this is Float && that is Float -> this that
else -> throw Exception("Types mismatch")
}
}
在上一頁。示例引數:
val n1 = 1230000000000000000L
val n2 = 123
val result = n1 infixPlus n2
result: -1313144709
沒有例外和錯誤的結果。
uj5u.com熱心網友回復:
您必須找到正確的結果型別:
val types = listOf("Double", "Float", "Long", "Integer", "Short", "Byte")
infix fun <T : Number> T.myPlus(that: T): T {
return when(types[min(types.indexOf(this.javaClass.simpleName), types.indexOf(that.javaClass.simpleName))]) {
types[0] -> (this.toDouble() that.toDouble()) as T
types[1] -> (this.toFloat() that.toFloat()) as T
types[2] -> (this.toLong() that.toLong()) as T
types[3] -> (this.toInt() that.toInt()) as T
types[4] -> (this.toShort() that.toShort()) as T
types[5] -> (this.toByte() that.toByte()) as T
else -> throw IllegalArgumentException()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483539.html
上一篇:泛型Java-獲取泛型的泛型型別
