Sunday, 1 January 2012

Mocking in Scala with ScalaTest and Mockito

It turnes out that mocking with Mockito in Scala is very simple. The only issue is the eq method which I had to map to the.
import org.mockito.Matchers.{eq => the, any}

Dependencies

To use ScalaTest with Mockito you need the following dependencies:
  "org.scalatest" %% "scalatest" % "1.6.1" % "test",
  "org.mockito" % "mockito-core" % "1.9.0" % "test",
Have a look at the example:

Thursday, 29 December 2011

SaveAs for Strings in Scala with "Pimp my library" pattern

Problem

Have you ever wanted to save a string to a file? Well, it's one of this things you don't want to do in 3 lines of code like this:
val f = new FileWriter("some/file/name.txt")
f.write("My string I want to save")
f.close()
I would rather see it like that:
"My string I want to save".saveAs("some/file/name.txt")

Solution

Luckily in Scala we can use "pimp my library" pattern. It uses implicits to convert String to RichString containing the saveAs method:

Monday, 26 December 2011

Matrix multiplication in Scala

First take with idiomatic scala(77ms):


Second take - replacing fors with whiles(63ms):


Third take - sum in a variable(55ms):
Multi-threaded with parallel collections(15ms): Multi-threaded with parallel collections idiomatic scala(32ms):

Sunday, 25 December 2011

Lazy prime numbers in Scala


The key to understanding this example is the #:: operator. It is very similar to :: for collections. The difference is that it doesn't evaluate the right hand side argument immediately. Instead it keeps it's reference as a function and evaluates it only when needed. The evaluation is deferred until the actual element is needed.

Alternative to try-catch in Scala

I just saw such a nice control abstraction in Scala, that I wanted to share it. The original idea comes from akka-samples, I just modified it slightly to be more generic.


In this example the otherwise block gets executed only if system throws ClosedChannelExeption, but I could easily imagine other control abstractions hiding different exception types.

Scala block gotcha

Do you know what this line of code is going to print?
List(1,2,3).map{println("Adding 2"); _+2}

My first answer would be: 3 times "Adding 2".

Lets see:
scala> List(1,2,3).map{println("Adding 2"); _+2}
Adding 2
res11: List[Int] = List(3, 4, 5)

Hmm, it prints "Adding 2" just once...
So what is really happening here?

The cue is in understanding what is the semantics of a block in Scala.

The map function on List expects a function Int => B. The block {println("Adding 2"); _+2} is not a function Int => B. It's just a block of code which gets evaluated and returns value of the last expression. In our case when the block gets evaluated it prints "Adding 2" and then it returns a function x => x+2 (shorter _+2). Then this function is called 3 times to map elements of the list.

What is the workaround?

We just need to make sure that println is in the body of the function, that we pass to map, i.e.
scala> List(1,2,3).map{x => println("Adding 2"); x+2}
Adding 2
Adding 2
Adding 2
res12: List[Int] = List(3, 4, 5)

Enjoy!

Context bounds for type parameters in Scala

I thought I knew all type parameter bounds until recently, when I discovered the context bounds.

Let's have a look at the example:
def sum[T](list: Seq[T])(implicit typeClass : AddTypeClass[T]) = {
    list.reduce(typeClass.add(_,_))
  }

There is nothing unusual in here. Function sum needs a typeclass to perform it's operation.

Now let's express the same using context bounds:
def sum[T: AddTypeClass](list: List[T]) = {
    val typeClass = implicitly[AddTypeClass[T]]
    list.reduce(typeClass.add(_,_))
  }

Expression [T: AddTypeClass] means: "for some T such that, there exists a type AddTypeClass[T]". This is called context bounds.
Now we just need to get hold of an instance of type AddTypeClass[T]. We can use the function implicitly from Predef.

The definition of implicitly is as follows:
def implicitly[T](implicit e: T) = e

Enjoy!