demo-money-project/src/main/kotlin/com/example/demo/domain/Money.kt

41 lines
1.1 KiB
Kotlin

package com.example.demo.domain
class Money (
var value: Double = 0.0,
var currency: Currency = Currency.USD
) : StdMoneyFormatable {
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 getMoneyValue() = value
override fun getMoneyCurrency() = this.currency.name
override fun toString(): String {
return "Money(value=${formatMoneyValue()}, currency=$currency)"
}
}
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!")
}
}
}
}