Category Archives: scala

a small store application in scala, with play and akka

I’ve been promising some people that I would put a personal project I’m working on available on github. I wanted to have it done and usable before doing that, but since I always get delayed by something, I decided to make the source code available right away. So I did this last week and you can find it here. It is called “lojinha”, which stands for something like “small store” in Portuguese.

The goal of the project is to implement a personal auction system, so that I can sell my used stuff I don’t want anymore. As of now, the project uses Play Framework 2.0 and Akka. Slow tasks like image thumb generation are delegated to akka actors. Also, the whole project is written in Scala, my current language of heart.

I’m still choosing where I’m going to deploy my instance when the project is ready, but I’ll publish a link here when it happens, so that you can buy something if you want =). It will probably be Amazen EC2 or Heroku.

Finally, all feedback is welcome!


Slides from my Akka presentation at Just Java 2012

I just uploaded the slides from the Akka presentation I did at Just Java 2012. You can find them here. The slides are in portuguese because the audience were brazilians, of course ;)

By the way, the conference was really nice and I’ll probably write a post about it in the next few days.


Akka at Just Java 2012 in São Paulo

This weekend, 18th and 19th of May, will hold the Just Java 2012 conference down here in São Paulo, Brazil. If you are in the area, please drop by.

This year, I’ll give a presentation about Akka 2.0 – mainly focusing on vertical scaling. I don’t have the talk completely done yet, so if you have something you would like to see, please get in touch. Otherwise, see you there!


Scala 99 Problems on github

A long time ago I started playing with the scala 99 problems. The project is going very slow, but it is moving. So I decided to share the code in a more open and easier way: github. I have solutions for the first 6 problems there, and will be updating as I move along.

The repository can be found here.

If you have extra solutions for the problems that are already there, feel free to do a pull request. For now, I’ll be accepting only pull requests for problems I already solved somehow, since my goal is the try them myself before looking at other people’s solutions.

For you test-fanatics out there, all the code is test-driven, using specs2 =)


Why dynamic languages are not cool

Some people love dynamic languages. I don’t. This last week, I found one more reason for it. I might be a bit biased because I love Scala, but lets go for it.

A project I started maintaining a few weeks ago is written in python. I don’t know much python yet, so there is this fact in and by itself. And I must say I’m liking the language. Now, the fact that it is dynamic has already bitten me at least twice.

In one of those, I was trying to understand why a test I just wrote was not working. It was as if one line was being simply ignored… Well, looks like I discovered by accident that I can call methods that doesn’t exist, at least on some objects or classes. I had a misspelled method name. As soon as that was fixed, everything worked fine. Half an hour lost with a problem that the compiler / interpreter should really warn me about.

The other case was a property in an object that simply disappeared. At a certain point in a function, it was there. A few lines later, in the SAME function, it was not anymore. At least this time it was simple to find the problem: a reassignment was being made, which was changing the type of the object.

Again: changing the type of the object. With an assignment. Yes, from a static language lover, this just feels absurd. There is no way this was going to happen in a statically typed language.

Lets end this rant on a positive note. I am liking python. Still, I would like it much more if it was statically typed.

By the way, we are going to have a new scaladores meeting in Sao Paulo on Feb. 23th. If you are in the region by then, please stop by. More information (portuguese) here.


Matching a combination of class and trait in Scala

While doing some development with Scala I discovered that it is possible to match combinations of a class and traits. It might seem obvious if you already know it, but I didn’t.

What happened is that I needed something like matching that kind of combination… and this speaks to something about Scala that I love: it becomes intuitive after a while. So how did I find that such matching is possible? I simply tried… =)

This is what this feature looks like:

msg match {
  case x: X with Z => println("matching combination!")
}

In this case, X would be a class, and Z a trait. The case x will be triggered only if msg is an instance of class X and mixes in trait Z. With this, we make sure to have access to all members both from the class and from the trait, while being really type safe about the matching. No unsupported combinations will pass through, and no need for castings, like would be necessary in Java.

Lets try a dummy example. Imagine we have a Superman class, and two traits: BlueCape and RedCape, like the following code:

class Superman(val realname: String)
trait BlueCape
trait RedCape

Now, we want to match on a Superman instance, but we want to know if it is fake or not. Finally, we also want to print the guy’s name, which means we need access to the realname field. This is how you could do that:

def whichSuperman(superman: AnyRef) = superman match {
  case s: Superman with RedCape => println("real superman: " + s.realname)
  case f: Superman with BlueCape => println("fake superman: " + f.realname)
}

Flexible and type safe! And if the traits had any field, we would be able to access them as well. Quick sample test code:

val mys = new Superman("clark") with RedCape
val myf = new Superman("clurk") with BlueCape

whichSuperman(mys)
whichSuperman(myf)

The part that matches the class is not very useful in this example, since this could be defined in the function parameter, but it was in my local scenario, where we are using actors and the messages can be AnyRef.

If you want to know a bit more about pattern matching, I wrote about it a while ago here. I also described how to match a range of numbers here.


scaladores first meeting

Right to the point: we are starting a Scala user group down  here in São Paulo, called Scaladores. The idea is to for people interested in the Scala language to meet in person and talk about it. If you are in the region, please drop by – the first meeting happens this thurday, at 7pm. The portuguese page with more information can be found here.

I’ll come back after the meeting for a ‘report’ of how it went =)

In time: I should write more posts about scala soon, just need to get some stuff in place before that.


Acidental scala upgrade with sbaz

And then I was playing around with the scala tools that come in the installation’s bin folder. There is something there called sbaz, and this name sounds so different that I just HAD to play with it to find out what it does.

Lets first explain what I discovered later: what sbaz does. It is some kind of scala package manager for your local scala installation. If you issue a sbaz available, it will list all packages it is able to install for you, for example. Also, and this was the somewhat tricky part for me, it is able to upgrade all current packages to their latest versions, including the main scala stuff, like the scala-library.

This is all great.. as long as you don’t run sbaz upgrade by mistake. This happened some weeks ago to me… And I was lucky enough to not have any major problem. I was running scala 2.8.0 at the time, and 2.9.0 was already out. Result: I upgraded to scala 2.9.0 before I intended to… and one day before a speech I gave at a conference, where I presented plenty of scala code examples.

In the end all went well, but I had to update some sample code, and to upgrade the Netbeans scala plugin to the version that supports 2.9.0. The other option would be to erase the installation folder and install scala from scratch again, but I chose to use this “event” to upgrade to 2.9.0 for real =)

Bottom line: learn that scala has a very nice package manager tool called sbaz, but use it with care ;)


Scala’s Parallel Collections are useful even in the most simple cases

One of the main features that Scala version 2.9.x brought was Parallel Collections. If you think about it quickly, you might consider using such a feature only in complex, process intensive scenarios.

Although those are certainly the main places where you would consider using parallel collections, there are more simpler ways you can leverage them. The code to use this feature is so simple that it’s easy to come up with reasons to use it everywhere:

myCol.par foreach(println)

Now how could that be easier??

So where did I use that for real, you might ask. The current company I work on stores files in Amazon S3. Before that, those files where stored in the local disk. So, when we migrated to S3, I wrote a script, in Scala, to upload all the files… thousands of them. My first solution looked something like this:

listOfFiles foreach(file => sendToS3(file))

And then suddenly it occurred me that it’s ridiculously simple to parallelize the upload of the files:

listOfFiles.par foreach(file => sendToS3(file))

Result: half the time for uploading the files, having to do almost nothing! Pretty neat, ain’t it?


Scala Problem Number Six

From the Scala 99 Problems, lets face the problem number six:

P06 (*) Find out whether a list is a palindrome.
Example:

scala> isPalindrome(List(1, 2, 3, 2, 1))
res0: Boolean = true

The first thing I had to do was to find out the meaning of palindrome. From the example, it’s easy to guess, but I prefer to be sure. So, from dictionary.com:

1. a word, line, verse, number, sentence, etc., reading the same backward as forward, as Madam, I’m Adam  or Poor Dan is in a droop.

Interesting, so this is valid not only for numbers =)

Now, to some coding! My first solution:

def isPalindrome(list: List[Any]): Boolean = list match {
  case Nil => true
  case head :: Nil => true
  case head :: rest if head == rest.last => isPalindrome(rest.dropRight(1))
  case _ => false
}

This first solution uses pattern matching to investigate the list recursively. It checks if the list is empty or if it contains only one element and returns true. Otherwise, it checks if the head of the list equals the last element. If so, the rest of the list (its middle part) is passed recursively to the function. This is one more case where we can see the great power of scala’s pattern matching in action.

Also, the solution will work with strings as well, so it matches the dictionary definition – just call toList on the string. Sample execution from the REPL:

scala> isPalindrome("oio".toList)
res11: Boolean = true

scala> isPalindrome("oioo".toList)
res12: Boolean = false

To be honest, I don’t feel too much creative when thinking about this problem, so the next solution is quite similar to the previous one, but without pattern matching:

def isPalindrome(list: List[Any]): Boolean = {
  if (list.isEmpty || list.size == 1) true
  else if (list.head == list.last) isPalindrome(list.slice(1, list.size-1))
  else false
}

Now lets take a look at the original solution and… I’m stunned by its simplicity. While I went all fancy at things like pattern matching, the original solution goes like this:

def isPalindrome[A](ls: List[A]): Boolean = ls == ls.reverse

Yeah, I should have thought of that…


Follow

Get every new post delivered to your Inbox.