Skip to content

Instantly share code, notes, and snippets.

@hussachai
Last active February 12, 2022 23:00
Show Gist options
  • Save hussachai/ac82e0ce29f890fce06db042634b74cb to your computer and use it in GitHub Desktop.
Save hussachai/ac82e0ce29f890fce06db042634b74cb to your computer and use it in GitHub Desktop.
data class Currency(val value: BigDecimal, val code: String) {
constructor(v: Int, code: String): this(BigDecimal(v), code)
fun convert(toCode: String): Currency {
return Currency(convert(this, toCode), toCode)
}
private fun convert(fromCurrency: Currency, toCode: String): BigDecimal {
//1 USD = 1.27082 CAD
return if (fromCurrency.code == "USD" && toCode == "CAD") {
fromCurrency.value * BigDecimal(1.27)
} else if (fromCurrency.code == "CAD" && toCode == "USD") {
fromCurrency.value / BigDecimal(1.27)
} else {
...
}
}
operator fun plus(that: Currency): Currency {
println(convert(that, this.code))
return Currency(convert(that, this.code) + this.value, this.code)
}
override fun toString(): String = "$value $code"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment