Archive for the ‘Scala’ tag
Scala Sugar – Iteration
In this second installment of Scala Sugar, lets put the lists that we created in the previous post to use.
How do we typically interact with lists when writing non-trivial programs? We iterate over them! With that being said, lets explore how iteration in Scala compares with iteration in Java.
Taking the lists in the previous post in to account, lets assign ourselves a task of iterating over each element in the list and converting them to uppercase.
First, we all know how to do this in Java using a standard for each loop:
for (String s : l) { System.out.print(s.toUpperCase()); }
There are so many different ways to iterate in Scala, thus we are only going to talk about the most trivial ways.
for (s <- l) print (s.toUpperCase())
-or-
l.map(_.toUpperCase()).foreach(printf("%s", _))
Download Source: simpleLists.scala
As you can see, you can loop in Scala the same way that you do in Java, namely, with a for each loop. There is nothing special about that.
The second loop is written in more a functional paradigm, as it uses the Scala map function. It allows you to iterate over the list without having to know anything about the details of the iteration itself. With Scala you are working at a much higher level. If we look at the Scala map function, it takes in a function as an argument, in this case the function is “toUpperCase()”. The map function then applies this function to all of the elements in the List, thus you don’t have to worry about the actual iteration logic. In this scenario, all the caller needs to worry about is that they have a List of elements, and they want some function f applied to all of them.
You can chain functions together on a List. In this case, we changed a foreach to the end of the map. If we were to describe the what is going on in plain english, it would sound something like, take all the elements of l, apply “toUpperCase” to all of them, then for each of them, print them.
The final interesting thing to notice in the above line of code is the “_” placeholder syntax. It looks strange to have a “_” there as part of the code, but all it is doing is acting as a placeholder for the function. It simply represents the current element of the List being operated on. Even though there are two “_”’s in this example, they are completely independent of each other. The placeholder is a very powerful advanced concept in Scala and this example barely touches the surface of its usage. We will talk more about it in a dedicated post.
As you can see, Scala supports both the “Java” way of iterating and a pure functional way. Again, this example is just one of the many different techniques for iterating in Scala. In a future post we will look at other ways of iterating in Scala.
References
- The code found in this post is hosted at github.com along with other sample Scala code.
Scala Sugar – Lists
If I want to become a real Scala Ninja, I am going to have change the way I think about coding. For the past 10 years I have been programming primarily using the object oriented paradigm. Although Scala supports pure object oriented programming, it is my desire to learn to program in Scala in a complete functional paradigm.
Of course, learning a new programming paradigm is not going to happen over night, it is going to take a bit of time. Over the course of the next few months, I am going to be posting a series of posts documenting my progress learning Scala. They will be written from the perspective of a “hardcore” Java programmer being enlightened by a sweet new language. I will write about all of the “sugar” Scala has to offer a Java programmer, and that is how I came up with title “Scala Sugar”.
In this first installment of Scala Sugar lets discuss one of the most fundamental concepts required to write any non-trivial program, namely Lists.
For the longest time, Lists in Java didn’t bother me at all, as they seemed “normal” to me. That was until I was introduced to dynamic languages a few years back. Now, Lists in Java seem extremely verbose to me as I wonder why in Java you can’t just create and populate a list with a single line of code. Lets look at our first Java vs Scala comparison.
Lets create a trivial list of three lowercase strings.
import java.util.ArrayList;
import java.util.List;
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
In Java it takes a minimum of 6 lines of code to declare a list of 3 strings!
Now lets declare the same list in Scala.
val l = List("a", "b", "c")
Download Source: simpleLists.scala
Thats it, one line of code!
The most important things to pay attention to are:
- No need to import List in Scala, as most fundamental classes are imported by default in Scala
- You do not have to give ‘l’ a type in Scala. Scala uses Type inference which means that it can infer its type from the object it is pointing to. It is important to realize that Scala is statically typed, it just doesn’t require you to type your variables when you define them. The compiler is smart enough to figure it out.
- You can construct a list with elements in Scala, no need to “add” each element separately.
Even in this trivial example, you can start to see how clean and concise Scala is.
In my next post we will explore different ways to iterate over the lists.
References
- The code found in this post is hosted at github.com along with other sample Scala code.
- Scala List API
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)
)
println(
portfolio.reduceLeft(
(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
- 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:
- 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 scala-lang.org.
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 github.com along with other sample Scala code.
Going Functional with Scala
Lately it seems like functional programming has been the talk of the town, the new (old) paradigm that is making a comeback in a major way. For a while, I resisted the urge to follow the paradigm de jour, being the hard core OO guy that I am, but now it is clear to me that it is more than just hype. There are many reasons functional programming makes sense as a paradigm for developing software today, but the one that I am most interested in is the fact that it handles concurrency so well, thus providing us the building blocks to develop extremely scalable applications.
FP (Functional Programming) has been on my mind for a while. The seed was placed there in late 2007 by the Java Posse listening to their interview with Martin Odersky. They were not talking about FP per se, but more about a specific JVM language called Scala (pronounced skah-lah not scale-la). Scala is not a pure functional language, it is actually a fusion between functional and object oriented programming. It brings together the best of both worlds. My exposure to Scala did not end there, as I got another huge dose at Java One 2008. Two of my favorite sessions there were either on Scala, or Scala was a major discussion point.
The first session was the Script Bowl. This session was not specifically about Scala, it was more of a JVM scripting language battle, and in the end JRuby was crowned king by the audience. In my mind, Scala was the clear winner, because of the simple, yet elegant and powerfull concurrency demonstrated. The presenter wrote what looked like a relatively simple program, and it was capable of indexing tons of RSS feed dumps in real time on a typical multi-core laptop computer. I remember thinking to my self, wow, it would take me a lot more time and effort to write a similar program in Java, and it probably wouldn’t have the same level of scalability as the one demonstrated. The Scala code was able to fully utilize the multi-core processors it was running on.
The second session was on Scala presented by the father of Scala him self Martin Odersky. During that session I was wowed again with some of Scala’s features like it:
- is scalable because it works for very small and very large systems.
- “is the Java programming language of the future.”
- is object oriented, functional, and a scripting language.
- leverages Actor’s as the primary concurrency construct.
- fits seamlessly in to a Java environment.
- is a composition language, as it adds the notion of Traits.
- has an updated type system supporting type inference.
After those two sessions, I headed over to the Java One bookstore to check out the Beta version of Programming in Scala. I was impressed, but couldn’t help thinking, is Scala for me? Can I use it at work? Is it viable in the enterprise?
Fast forward 7 months to today, and let me answer my own questions with one word: yes!
- Is it for me? Yes, because Scala is not only something new, it is something advanced, because it was written in a no compromise academic environment. If nothing else it is a great way to broaden my horizons as a programmer.
- Can I use this at work? Yes, Scala code compiles down to Java byte code, so theoretically, if I was very evil, I could write all my code at work in Scala, run Scalac on it, and add the class files to the application, and no one would be any the wiser. Will I do that? No way, I am simply trying to illustrate a point that Scala is totally compatible with any existing Java environment.
- Is it viable in the enterprise? Yes, with its advanced concurrency model, I can only imagine the type of throughput you can achieve. (Looking forward to finding out)
Now you know where my interest in Scala comes from. Hopefully after reading this post, you will be a bit curious about it as well.


