Scala Currency Class

Most of you probably ran into the well-known precision problems with floating point numbers at one time or another. If you haven’t, consider this example:

scala> 1.2 - 1.0
res1: Double = 0.19999999999999996

Oops. Shouldn’t that be 0.2? Yes it should, but since the number 0.2 cannot be represented exactly in binary form, the result is a little bit less. This problem becomes annoying when Floats or Double values are used to represent money. It gets worse when multiplication or division operations magnify the error, as for example in the case of interest calculations. Simply put, you can’t guarantee the exactness of calculations down to the cent when you represent monetary amounts as floating point values. The Java language has a type called BigDecimal which solves this problem. It offers arbitrary scale fixed point arithmetics that allows precise financial calculations. Unfortunately, Java’s BigDecimal class has a rather unwieldy API which is a pain to use. No problem, you may think, because Scala offers a wrapper for BigDecimal that lets you use it like a normal number. That is true, but try this out:

scala> val b: BigDecimal = 0.1
b: BigDecimal =

Oops again. This doesn’t look much better. What is more, the BigDecimal wrapper class in Scala has abstracted away the control over rounding behaviour and precision offered by the Java API. Of course, you could follow another approach and use Long values to represent money and scale them to the required precision, say one ten thousands of a Dollar. However, there are a number of problems with this approach. First, the value range is limited by MAX_LONG/scale. Second, you have to do complex formatting every time you print the values. Third, you have to code rounding manually because remainders are discarded in integer arithmetics:

scala> 59L / 10L
res2: Long = 5

With this in mind, I have created a Scala currency type that offers arbitrary precision fixed point arithmetics with an easy-to-use API. It is based on the Java’s BigDecimal type – why reinvent the wheel? Let’s repeat the first arithmetic operation using the currency type:

scala> Currency(1.2) - Currency(1.0)
res3: Currency = 0.20

This time the result is correct. It is correct, because the currency type automatically takes care of rounding. By default, the result is rounded to the second decimal place using the ROUND_HALF_UP rounding mode, which means that 1.555 is rounded to 1.56 and -1.555 is rounded to -1.56. Unlike the rounding for Float and Double values, the rounding is symmetric, which is standard in most financial calculations. If you need a different rounding behaviour – no problem. With the currency type, you have complete control over precision and rounding behaviour.

scala> val c = Currency("1234.56789", 4)
c: Currency = 1234.5679

scala> val d = Currency(0.1, 20)
d: Currency = 0.10000000000000000000

scala> import Currency.RoundingMode._
scala> val e = Currency(22.78, 2, ROUND_DOWN)
e: Currency = 22.78

The first expression creates a currency value with a precision of 1/10000 (= four places right of the decimal point) from a string argument where the fifth decimal place is rounded up in construction. The second expression creates a value of 0.1 (10 cents) with a precision of 10-20 or 20 places after the decimal point. The third expression constructs a value of 22.78 with a special rounding mode that stipulates that values should always be rounded down. The effect can be seen when performing an arithmetic operation:

scala> e * 1.1
res4: Currency = 25.05

scala> val f = Currency(22.78, 2, ROUND_UP)
f: Currency = 22.78

scala> e == f
res5: Boolean = true

scala> f * 1.1
res6: Currency = 25.06

In this example, the first operation e * 1.1 yields 25.05. We create another currency object with the same value, however with a different rounding mode. When performing the same operation on the second value f, the result differs by one cent from the first because it was rounded differently. This means that arithmetic operations with currency values that have different precision and/or rounding modes are not transitive. This is of course intended behaviour. The above examples show simple calculations with non-specific currency values. In addition to the numeric amount, the currency type optionally takes a currency designation in the form of an ISO 4217 three-letter code. For example:

scala> val salary = Currency(4789.90, "USD")
salary: Currency = 4789.90 USD

scala> val bonus = Currency(500, "USD")
bonus: Currency = 500.00 USD

scala> val holidayInEurope = Currency(2400, "EUR")
holidayInEurope: Currency = 2400.00 EUR

scala> salary + bonus
res7: Currency = 5289.90 USD

scala> salary + holidayInEurope

You can add, subtract and compare amounts in the same currency (or of a non-specific currency value), but when you try to add two different currency values, you get an exception. Alternatively, different currencies could be implemented as different subtypes, as suggested in Ch.20, Programming in Scala (Odersky, Spoon, Venners). This has the advantage that currency mismatches can be detected at compile time. However, it complicates the design and makes mapping the currency type to a database rather awkward. I think that the disadvantages outweigh the benefits, so I implemented the currency type as a “monolithic” class that knows about all currencies. With this design, it becomes easy to format currency values for output.

scala> salary.format
res8: String = $4,789.90

scala> import java.util.Locale
scala> holidayInEurope.format(new Locale("de", "DE"))
res9: String = 2.400,00 €

scala> holidayInEurope.format(new Locale("fr", "CH"))
res10: String = € 2'400.00

scala> salary.format("\u00A4 #,##0.0000")
res11: String = $ 4,789.9000

The currency class offers a severalfold overloaded format method that formats currency amounts according to either the default locale or a chosen locale. Alternatively, you can specify a formatting pattern and/or symbols to use, or you can use Java’s DecimalFormat class for formatting. Thus you have total control over the formatted output. The currency class can also verbalise amounts in four languages.

scala> salary.say
res12: String =
  four thousand seven hundred eighty nine Dollars ninety Cents

scala> salary.sayNumber
res13: String =
  four thousand seven hundred eighty nine 90/100

scala> val pesos = Currency("1538.20", "MXN")
pesos: Currency = 1538.20 MXN

scala> pesos.say(new Locale("es"))
res14: String =
  mil cincocientos treinta y ocho Mexican Peso veinte Centavo

scala> pesos.sayNumber(new Locale("es"))
res15: String = mil cincocientos treinta y ocho 20/100

Finally, the currency class provides a number of convenience methods, such as percentage(), setDecimals(), abs(), fraction(), integral(), pow(), symbol(), getAllCurrencies(), etc., and a number of factory methods and conversion methods to simplify programming with currency values.

View Source Code.

Download full source code and API documentation.

Scala Hits Top 30

The Scala programming language has for the first time hit the top 30 of the TIOBE index in April this year. The TIOBE index measures the popularity of programming languages by counting searches for the respective programming language in the most popular search engines. In April 2009, Scala searches were tracked at 0.237% of all searches which places it at rank 28. This means it is already ahead of other functional languages such as Haskell, Erlang amd Caml. The TIOBE track record is an indicator of Scala’s growing popularity. Scala entered the TIOBE index in early 2008 and appeared in the Top 50 for the first time in the fourth quarter of 2008.

Scala Tutorial (3)

Now that we have covered the somewhat “dry” foundations of the Scala language, let’s move on to the good stuff. That is to say, let’s move on to the functional aspects of Scala. Some of these may appear foreign to you if your main language is object-oriented or procedural. They definitely appeared foreign to me at first. It cannot be stressed enough that functions are primary language constructs in Scala. I mentioned function literals. Here is an example:

(x: Int) => x - 1

A function literal is simply a function without a name. You can assign this expression to an ordinary variable and then use it later to execute the function:

var decrease = (x: Int) => x - 1

You can probably guess what the value of decrease(11) is. Up to this point, this isn’t very exiting. However, because decrease is a var and not a val, you can reassign it a different function literal later on depending on some condition. Or you could pass it as an argument to another function. You might begin to see the possibilities behind the first class function concept. Instead of the trivial example above you can use this capability with more complex methods. For example, you could use it for callback methods, or for wrapping methods in an API and facilitating common OOP patterns, such as the facade and adapter patterns. All of this can be done, unlike in Java, with a minimum of syntactical fuss.

But it gets even better. Functions in Scala are not limited to use simple parameters as in the above example. For example, you could write something like this:

var decrease = (x: Int) => x – something

Obviously, the variable something, which is subtracted from x is not defined in this expression. The assignment is still syntactically valid. This means the variable decrease is properly defined, but it cannot be applied. In other words, to apply a value or to execute the function meaningfully, it must be executed in a context where something is defined. The above expression is an “open term” and something is called a “free variable”. An open term is the principal ingredient of a closure. Simply put, a closure closes an open term by providing the necessary context. This is an example of a closure:

something = 10

The first line defines the free variable something. The second line therefore produces a meaningful value. That’s the closure. In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context. It’s like an inner class in Java that references variables of its outer class. However, the Scala construct is more powerful and much easier to write. It can be useful in a number of situations where the place where behaviour is defined is removed from the place where the behaviour is applied.

While closures are supported by languages that one wouldn’t consider functional programming languages, higher-order functions are a hallmark of the functional paradigm. The concept is simple enough. A higher-order function is a function that either takes one or more function parameters or returns a function, or both. The prime example would be the map function. The map function takes an list as input and produces an output list using a specific algorithm. The algorithm is of course represented by another function that is passed as a parameter to the map function. In Java, this would typically require a the use of a for loop or an iterator. In Scala, the mapping can be expressed succinctly with a single line. Here are some examples:

scala> List("alpha", "beta", "crash").map(
  p => p.substring(0,1))
res0: List[java.lang.String] = List(a, b, c)

scala> List(1, 2, 3) map (_ * 2)
res1: List[Int] = List(2, 4, 6)

scala> List("Tango", "Mango", "Bobo", "Gogo")
    map (_.endsWith("go"))
res2: List[Boolean] = List(true, true, false, true)

These examples are quite trivial, but they illustrate the basic idea of higher-order functions. The first line maps a list of strings to another list of strings. The result elements retain only the first characters. The second line is produced by the interactive Scala Interpreter; it displays the result of the expression. A function literal is used as the parameter of the map function in line 1. Line 5 and 9 make use of the underscore notation which is a placeholder for the bound variable, which is the list element parameter in this case. Thus (_*2) is equivalent to (i => i * 2).

Higher-order functions are not just a succinct form of control abstraction. They are also very useful for reducing code duplication and redundancy. The typical use case is abstracting behaviour. There are a number of design patterns for abstracting behaviour which are popular in languages like C++ or Java, such as the strategy pattern. Consider the following Java example:

import java.util.*;

interface FileNameMatcher {
  boolean matchFileName(String fileName, String query);

class FileNameMatcherEnding implements FileNameMatcher {
  public boolean matchFileName(String fileName,
    String query) {
    return fileName.endsWith(query);

class FileNameMatcherContaining implements FileNameMatcher {
  public boolean matchFileName(String fileName,
    String query) {
    return fileName.contains(query);

class FileNameMatcherRegex implements FileNameMatcher {
  public boolean matchFileName(String fileName,
    String query) {
    return fileName.matches(query);

public class FileMatcher {

  public static String[] filesMatching(FileNameMatcher
    fileNameMatcher, String query) {
    File[] files = new File(".").listFiles();
    List matchResult = new ArrayList();
    for (File thisFile : files) {
        thisFile.toString(), query))
    return matchResult.toArray(new String[] {});

  public static void main(String[] args) {
    String query = args[0];
    String[] matchingFiles;
    matchingFiles = filesMatching(
      new FileNameMatcherEnding(), query);
    matchingFiles = filesMatching(
      new FileNameMatcherContaining(), query);
    matchingFiles = filesMatching(
      new FileNameMatcherRegex(), query);


This is a classic example of the strategy pattern. The core piece of this code is the one-method interface named FileNameMatcher. This interface abstracts different ways to match a file name. The three implementing methods match a file name either by looking whether a file name ends with a given string, whether it contains a given string, or whether it matches a regular expression. The filesMatching() method of the FileMatcher class takes a strategy implementation and applies it to a list that contains all files in the current directory. Finally, the main() function calls the FileMatcher with the three different strategy objects that were defined earlier. All together that’s 55 lines of Java code. Compare this to the Scala equivalent which appears in the book Programming in Scala by Odersky, Spoon and Venners (page 199):

object FileMatcher {

  private val filesHere=(new".")).listFiles

  private def filesMatching(matcher: String => Boolean)=
    for (file <- filesHere; if matcher(file.getName))
      yield file

  def filesEnding(query: String)=
  def filesContaining(query: String)=
  def filesRegex(query: String)=

object Main {
  def main(args: Array[String]) {
    val query = args(0);
    var matchingFiles = FileMatcher.filesEnding(query)
    matchingFiles = FileMatcher.filesContaining(query)
    matchingFiles = FileMatcher.filesRegex(query)

Brevity is the soul of wit. Obviously, there is no need to create strategy objects in Scala. With higher-order functions, the strategy pattern simply evaporates. This is one of the areas where Scala's powerful language constructs eliminate the need for patterns. Critical voices have said that design patterns are crutches for weaknesses in certain programming languages. Although I don't fully agree with this statement, it seems to hold true in case of the strategy pattern. The above Scala example is actually more verbose than necessary. One could make the filesMatching() method public and call it directly with a function parameter from outside the FileMatcher object. At the cost of full encapsulation, this would make the code three lines shorter.

Java vs. PHP vs. Scala

I have a bit of a dilemma with programming languages. Next year, I expect to be able to free up a little extra time for a private programming project (call me an optimist!) and I am wondering which language/technology to use. The project is quite straightforward. It's a business application that I use for my own work as a software engineer. It consists of four components. There's a contact manager component (or CRM as it's now fashionably called), a project management component, a time tracking component, and a billing component. That may sound like a tall order, but obviously I don't need the full-blown functionality of applications like Siebel, MS Project, or SAP. I just need an application that brings certain functionality together in a quite specific way to suit my needs.

The software I am currently using for this purpose consists of two different programs. The CRM and billing components are contained in a Delphi application which I wrote more than 10 years ago. The time sheet and project management components are part of a PHP application that I developed in 2002. Needless to say that these two programs are neither cutting-edge, nor are they well integrated. The Delphi application uses an outdated Borland Paradox DB  and the PHP application contains large swathes of ugly procedural code. Although the whole shebang fulfils its purpose, I feel it's high time for a replacement. Of course, I could acquire an existing software package and save a lot of time writing code myself. But hey, I am a software engineer. I do like a creative challenge and I want something that fits my needs. I also want to learn new technologies.

The question I am asking myself now is what to use for the task. I am considering Java, PHP, and Scala. There are pros and cons for each of these:

(1) Java, JSP and a web framework with an app server. This is the obvious choice. Most of my professional work is JEE-based these days. I believe that I can work productively with Java, although the language inevitably involves a lot of boilerplate code and redundancy, which has a negative impact on productivity. In spite of this, it would be an good opportunity to deepen my knowledge of JSF (Java Server Faces), Hibernate, or try out some other persistence layer. It would also offer an opportunity to learn a new Java web framework that I haven't yet worked with such as Spring or Tapestry. From a business point of view, this may be a good choice because Java technologies are in high demand and it is also a very robust platform. The JEE universe is really quite large and there's enough territory that would be fun to explore. The downside is that Java, the language, is slightly tedious.

(2) The second choice is PHP and the Zend framework in combination with some AJAX toolkit, such as YUI or Dojo. I have the feeling this would be the most productive way to go; the biggest bang for the buck so to speak. For a project of this size (around 50 kloc), the development time may be even half of that with Java. PHP 5 and the Zend framework are mature technologies and I am quite familiar with both. Another advantage of PHP is that it's wide spread. Almost every hosting company offers PHP, whereas the number of Java hosting companies is considerably smaller (and usually more expensive). So, there wouldn't be any problem hosting the finished product anywhere. The downside is that PHP, being a dynamic language, is less robust  and slower than JVM bytecode. The language is also less expressive. But the biggest disadvantage is that I'd hardly learn anything new in the process.

(3) The third alternative is using Scala in combination with the Lift framework and a standard web container. I find this the most exciting choice, but it's very likely to be the most time consuming. I am rather new to Scala and functional programming. What I have seen so far is great. Programming in Scala is much more fun than coding in Java or PHP. I am afraid though, it would take a bit of time to wrap my head around it and work productively. Scala is still a foreign language to me. Another downside is that there is a limited choice of frameworks, APIs, and tools available at this point. Actually, Lift is the only Scala web framework I know of. Another question I am asking myself is whether acquiring Scala skills does make any business sense. I haven't seen too many Scala job offerings so far. Seems like the most fun choice, but also the least promising from a business point of view. Decisions, decisions, decisions…

Scala Tutorial (2)

Scala is a purely object-oriented language in the sense that all language constructs are objects. This includes all primitive type values, such as Char, Int, Long, Float etc. For example, it is perfectly legal in Scala to append a method call to a literal primitive value, as in 3.1415.round or 88.max(99). Scala defines the following basic types:

Byte     8-bit Integer (-2^7 to 2 ^7-1)
Short    16-bit Integer (-2^15 to 2^15-1)
Int      32-bit Integer (-2^31 to 2^31-1)
Long     64-bit Integer (-2^64 to 2^64-1)
Char     16-bit Unicode character (0 to 2^16-1)
String   A sequence of Chars
Float    32-bit IEEE 754 single-precision floating point number
Double   64-bit IEEE 754 double-precision floating point number
Boolean  Logical value (true or false)

These data types are defined in the package scala, which is imported automatically along with scala.lang by the compiler. Extended functionality for these types (such as the cited max() function) is available via the scala.runtime API. Each type has an associated “rich wrapper class”, e.g for String there is a RichString class, for Int there is a RichInt class, and so on. Unlike Java, Scala does not distinguish between objects and primitive types. This implies that there are no boxing and unboxing functions and thus less to worry about the semantic details of these operations. Everything is simply an object. Behind the scenes the compiler performs optimisations that amount to auto-unboxing when arithmetic expressions are evaluated. Hence, the expression a + b * c which is equivalent to method calls b.*(c).+(a) is actually resolved to a primitive type arithmetic, just like in Java.

Scala is not only object-oriented in the sense that all variables are objects, irrespective of type, but that all functions including methods are also objects. Since functions and methods are objects, they are treated just like regular variables, which means that functions can be assigned to variables. They can also be used as parameters in function calls or as return values of functions and methods. A function value in the position of a function parameter creates a so-called higher-order function. In addition, Scala has a construct called a function literal which is basically a nameless function used in place of a function value, a bit like an anonymous method in Java, although the former are a lot more versatile. Furthermore, operators in Scala are methods. This makes some sort of operator overloading possible. Since +,-,*,/ etc. are just methods with funny names, you can define operators for your own data types. It is therefore possible to extend the language by adding APIs that contain class definitions for new data types along with their operators. This is illustrated by the following class definition for rational numbers. Rational numbers can be expressed as a fraction of two integer numbers. The following class defines the data type Rational as well as the four basic arithmetic operations for rational numbers:

class Rational(numerator: Int, denominator: Int) {

  require(denominator != 0)

  private val gcd = greatestCommonDivisor(numerator.abs,
  val n = numerator / gcd
  val d = denominator / gcd

  def this(n: Int) = this(n, 1)

  private def greatestCommonDivisor(a: Int, b: Int): Int =
  if (b == 0) a else greatestCommonDivisor(b, a % b)

  def + (that: Rational): Rational =
  new Rational(n * that.d + d * that.n, d * that.d)

  def - (that: Rational): Rational =
  new Rational(n * that.d - d * that.n, d * that.d)

  def * (that: Rational): Rational =
  new Rational(n * that.n, d * that.d)

  def / (that: Rational): Rational =
  new Rational(n * that.d, d * that.n)

  override def toString = n + "/" + d

The first line contains the head of the class with the so-called primary constructor, which is part of the class declaration in Scala. The expression in parentheses accepts two integer numbers that constitute the numerator and the denominator of the fraction. The next line that starts with require tests the denominator for zero and throws an exception if denominator = 0. As you can see, exceptions don’t need to be declared in the head of the class definition in Scala. The following three lines reduce the fraction by calculating the greatest common divisor and subsequently dividing the numerator and denominator by the result. These first four lines are not enclosed by a function definition block or any other block and thus constitute the body of the primary constructor. Next follows what’s called a auxiliary constructor in Scala. Auxiliary constructors are easy to spot, because they always start with this(). The expression def this(n: Int) = this(n, 1) provides a constructor that accepts a single integer number as an argument. This makes it easy to represent integer numbers as fractions where needed simply by setting the denominator implicitly to 1. For example, the expression new Rational(2,3) results in 2/3 and the expression new Rational(2) results in 2/1.

The method definition that follows the constructor code computes the greatest common integer divisor of two numbers using recursion. Since the recursive invocation stands in tail-call position in this instance, the Scala compiler optimises the generated byte code  internally and creates a loop instead of a recursive function call. The four methods after the greatestCommonDivisor() method define the four basic arithmetic operations for fractions. In case of addition and subtraction, the numerators and denominators of both operands are multiplied with each other before the sum of the numerators is calculated. In doing so, Scala makes use of built-in operator precedence (* and / before + and -), which is determined lexically if the function or method name begins with a special operator characters. The expression  n * that.d + d * that.n, is thus executed as n.*(that.d).+.(d.*(that.n)). Multiplication and division are even easier to implement as the two fractions are simply multiplied by each other, or respectively multiplied by the reciprocal value. The results are then returned as new Rational objects. Since the constructor finds the GCD of the two integer numbers, the resulting fraction is automatically reduced. Finally, the last method toString outputs the fraction in a readable form. Overridden methods must be marked with the override keyword in Scala. Functions that don’t take arguments are written without parentheses, hence toString() becomes toString.

Class Hierarchy

Scala HierarchySimilar to Smalltalk, every class inherits from a single common superclass. The universal superclass is named Any in Scala. This is to say that any datum in Scala is of the type Any. The subclasses of Any fall into two categories: AnyVal (value) and AnyRef (object reference). The above listed basic data types, as well as the primitive types in Java, such as byte, int, float, etc., are direct descendants of AnyVal, while all other types are descendants of AnyRef. The Scala type AnyRef is therefore conceptually identical with java.lang.Object and it comes with analogous methods, e.g. equals(), hashCode, clone, wait, etc. Some of these are actually defined further up in the hierarchy, namely in Any. In addition, Scala defines the type scala.scalaObject which provides the common superclass for all objects in the Scala APIs. This works because Scala allows multiple inheritance via so-called traits. This will be explained later in more detail.

The nesting of this type hierarchy allows interoperability wit Java. For example:

var a: int = 2    // Java Integer
var b: Int = 3    // Scala Integer
println(a + b)    // 5

In addition, it is possible to use Java collections for storing Scala data types, or Scala collections for storing Java data types. Furthermore, Scala has several special data types. For example, scala.Null is defined as subtype of any class that derives from an object reference scala.AnyRef. It is analogous to the null literal in Java and can thus be assigned to object references. The type scala.Nothing is defined as a subtype of all types; it is employed in exceptions where an expression does not return a type. This happens situations where an exception is thrown in a place where a value is expected. Finally, there is the type scala.Unit that is used for functions that don’t return a value. This is Scala’s concession to imperative programming. It is analogous to the void keyword in Java.