41 lines
1.2 KiB
Kotlin
41 lines
1.2 KiB
Kotlin
package com.example.demo.domain
|
|
|
|
class MoneyDyn(
|
|
var value: Double = 0.0,
|
|
var currency: String = "USD"
|
|
) {
|
|
|
|
fun addMoney(other: MoneyDyn): MoneyDyn {
|
|
this.value = this.value.plus(exchange(other, this.currency))
|
|
return this
|
|
}
|
|
|
|
fun exchange(fromMoney: MoneyDyn, exchangeCurrency: String): Double {
|
|
if (!fromMoney.currency.equals(exchangeCurrency, ignoreCase = true)) {
|
|
val rateFrom = MoneyConfig.getRate(fromMoney.currency)
|
|
val rateTo = MoneyConfig.getRate(exchangeCurrency)
|
|
return computeRate(amountFrom = fromMoney.value, rateFrom = rateFrom, rateTo = rateTo)
|
|
}
|
|
return fromMoney.value
|
|
}
|
|
|
|
fun exchangeTo(toCurrency: String): MoneyDyn {
|
|
return MoneyDyn(value = exchange(this, toCurrency))
|
|
}
|
|
|
|
private fun computeRate(
|
|
amountFrom: Double = 1.0,
|
|
baseRate: Double = 1.0,
|
|
rateFrom: Double,
|
|
rateTo: Double
|
|
): Double {
|
|
return amountFrom * ((baseRate / rateFrom) / (baseRate / rateTo))
|
|
}
|
|
|
|
private fun isEqualCurrency(other: MoneyDyn) =
|
|
this.currency.equals(other.currency, ignoreCase = true)
|
|
|
|
override fun toString(): String {
|
|
return "MoneyDyn(value=$value, currency='$currency')"
|
|
}
|
|
} |