including Double.2 The formatted method returns the string that results from formatting the original string on which formatted was invoked according to a format string passed as the formatted method’s right-hand operand. The syntax of format strings passed to formatted is the same as that of Java’s String.format method. For instance, the format string %.2f formats a number with two decimal digits. The format string used in the toString shown previously is assembled by calling the decimals method on CurrencyUnit.amount. This method returns the number of decimal digits of a decimal power minus one. For instance, decimals(10) is 1, decimals(100) is 2, and so on. The decimals method is implemented by a simple recursion:
private def decimals(n: Long): Int =
if (n == 1) 0 else 1 + decimals(n / 10)
Listing 20.12 shows some other currency zones. As another refinement you can add a currency conversion feature to the model. As a first step, you could write a Converter object that contains applicable exchange rates between currencies, as shown in Listing 20.13. Then, you could add a conversion method, from, to class Currency, which converts from a given source currency into the current Currency object:
def from(other: CurrencyZone#AbstractCurrency): Currency = make(math.round(
other.amount.toDouble * Converter.exchangeRate (other.designation)(this.designation)))
The from method takes an arbitrary currency as argument. This is expressed by its formal parameter type, CurrencyZone#AbstractCurrency, which indicates that the argument passed as other must be an AbstractCurrency type in some arbitrary and unknown CurrencyZone. It produces its result by multiplying the amount of the other currency with the exchange rate between the other and the current currency.3
The final version of the CurrencyZone class is shown in Listing 20.14. You can test the class in the Scala command shell. We’ll assume that the
2Scala uses rich wrappers, described in Section 5.9, to make formatted available.
3By the way, in case you think you’re getting a bad deal on Japanese yen, the exchange rates convert currencies based on their CurrencyZone amounts. Thus, 1.211 is the exchange rate between US cents to Japanese yen.