Scala reduceLeft

This post was updated on November 19, 2009.

As you know, during the past few weeks (time permitting), I have been spending time studying the Scala programming language. After reading the first few chapters of Programming In Scala, I have come across the first feature of Scala that would have been totally useful for me on one of my Java programming tasks a few months ago.

The actual programming task was quite complex, but for the purposes of this post, we will work with a dramatically simplified example. The simplified task is: given a list of Stocks figure out which one has the highest earnings per share.

Here is one way the problem can be solved in Scala:

class Stock(val ticker: String, var price: Double, var earnings: Double, var shares: Int) {
    override def toString = ticker + " has eps of: " + eps + " with a price of " + price
    def eps = earnings / shares
    def >(that: Stock): Boolean = {eps > that.eps}

  val portfolio = List(
    new Stock("aapl", 203, 4.73E9, 878876000),
    new Stock("ibm", 66, 1.23E10, 1384331000),
    new Stock("goog", 465, 4.19E9, 314754113)

        (s1, s2) => if (s1 > s2) s1 else s2
  // goog has eps of: 13.31

Download Source: Stock.scala, reduceLeft.scala

If you have never seen Scala code before, this code will look quite foreign to you because there are a lot of concepts in Scala that are not present in Java. In a few weeks (again time permitting), will begin writing a series on Scala for Java programmers, but for right now, please bear with me, and try to follow along.

The most interesting things to me about this code are:

  • Line 04: You are reading it correct, that is operator overloading!
    • Correction: Scala doesn’t actually support “operator overloading”, in fact, “operators are not special language syntax”. In Scala any method can be an operator. What makes an operator an operator is how you use it. Example:
1 + 2 //operator
1.+2 //not operator (but returns wrong type)
(1).+(2) // Correct return type
  • Line 07: It is great to be able to populate a list so easily without having to mess around with add methods.
  • Line 14: This is the coolest feature of them all so far, the ability to reduce a list of elements down to one based on a binary operator.

This is just a small demonstration of the very basics of the Scala language. If you find this at all interesting, you can find out much more at

Note: obviously, this is not the most optimal Scala solution so if your a Scala guru, criticisms are welcome. I hope to come back to this example every few weeks, continually improving it as my knowledge of Scala grows.

References The code found in this post is hosted at along with other sample Scala code.

comments powered by Disqus