47 lines
1.3 KiB
Kotlin
47 lines
1.3 KiB
Kotlin
package com.example.demo.domain
|
|
|
|
class Money (
|
|
var value: Double = 0.0,
|
|
var currency: Currency = Currency.USD
|
|
) {
|
|
companion object {
|
|
private const val MONEY_SPLITTER = ':'
|
|
fun parse(value: String): Money {
|
|
val temp = value.split(MONEY_SPLITTER)
|
|
if (temp.size == 2) {
|
|
return Money(value = temp[0].toDouble(), currency = Currency.create(temp[1]))
|
|
} else {
|
|
throw IllegalArgumentException("money is not valid!")
|
|
}
|
|
}
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return "Money(value=$value, currency=$currency)"
|
|
}
|
|
|
|
fun addMoney(value: Money): Money {
|
|
if (value.currency == this.currency) {
|
|
this.value = this.value.plus(value.value)
|
|
} else {
|
|
throw IllegalArgumentException("currency ${value.currency.name} is not matched!")
|
|
}
|
|
|
|
return this
|
|
}
|
|
}
|
|
|
|
enum class Currency (val symbol: Char, val displayName: String) {
|
|
USD('$', "Dollar"),
|
|
KHR('R', "Riel");
|
|
|
|
companion object {
|
|
fun create(value: String): Currency {
|
|
return try {
|
|
valueOf(value)
|
|
} catch (ex: Exception) {
|
|
throw IllegalArgumentException("currency is not valid!")
|
|
}
|
|
}
|
|
}
|
|
} |