我想實作一些可以使用 anInt或BigDecimaltype呼叫資料類的東西。例如:
data class Money(val amount: Int, val currencyCode: CurrencyCode) {
fun toSmallestUnit(): Int = when (this.currencyCode) {
CurrencyCode.USD -> this.amount * 100
CurrencyCode.EUR -> this.amount * 100
}
}
在這里,我希望能夠將兩者Int和BigDecimal數量都發送到 data class Money,然后toSmallestUnit為每種型別具有不同的功能。我如何在 Kotlin 中實作這一目標?
uj5u.com熱心網友回復:
一種方法是這樣的
data class Money<T>(val amount: T, val currencyCode: CurrencyCode) {
fun toSmallestUnit(): T = when(amount) {
is Int -> {
when (this.currencyCode) {
CurrencyCode.USD -> (this.amount * 100) as T
CurrencyCode.EUR -> (this.amount * 100) as T
}
}
is BigInteger -> {
when (this.currencyCode) {
CurrencyCode.USD -> this.amount.multiply(BigInteger("100")) as T
CurrencyCode.EUR -> this.amount.multiply(BigInteger("100")) as T
}
}
else -> {
amount
}
}
}
toSmallestUnit將根據型別回傳正確的結果型別。但是正如你所看到的,它允許創建Money任何型別
uj5u.com熱心網友回復:
每次在代碼中使用此類時,編譯器都必須知道哪種型別amount適合您,以便您能夠使用它做任何事情。如果我們使用您自己的類,您可以定義一個它們都實作的介面,但這對于 Int/BigDecimal 是不可能的。
因此,我建議您將類設計為簡單地使用 BigDecimal 作為 的型別amount,并提供建構式和屬性以允許它從 Int 轉換。
這只是一個例子。我不確定將 BigDecimal 中的貨幣轉換為整數有什么意義。
data class Money(val amount: BigDecimal, val currencyCode: CurrencyCode) {
constructor(amount: Int, currencyCode: CurrencyCode): this(amount.toBigDecimal(), currencyCode)
val intAmount: Int get() = amount.toInt()
fun toSmallestUnit(): Int = when (this.currencyCode) {
CurrencyCode.USD -> intAmount * 100
CurrencyCode.EUR -> intAmount * 100
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323562.html
