Sunday, 24 March 2013

The simplest dynamically typed json parsing with Dynamic in Scala 2.10

I love the way dynamically typed languages handle json or xml parsing. With Scala 2.10 we can do it using Dynamic trait. Here is a first draft.
Please feel free to copy/paste/reuse at your own risk.

The simplest Async Scala Http Client working with 2.10

This client is not the most efficient or the most async but it works and I am using it for testing my apps. Please feel free to copy/paste/reuse at your own risk.

Tuesday, 6 March 2012

Atomic update of AtomicReference

Problem

I like the AtomicReference class. When used with a immutable class, it offers quite a nice and efficient abstraction for concurrent data structure. One thing it is missing, in my opinion, is the atomic update method, ie.
  val list = new AtomicReference(List(1,2,3))
  list.update(list => list.map(_ *2))

Solution

You just need to import the Atomic class, and it will pimp the AtomicReference, so you can call the update method. See below: Enjoy!

Monday, 30 January 2012

Managing of opening and closing multiple resources automatically in Scala

Problem

Managing opening and closing multiple resource automatically. For example when you want to copy a file you need to open and close both input and output files.

Solution

I recently came across scala-arm library written by Josh Suereth. I liked the idea so much that I wanted to experiment with writing something similar, but a bit simpler myself.

Here is what I came up with:

Explanation

The magic is in the foreach method and the way the for and map work. They both use the foreach method. We are using this fact and wrapping the iteration with try-finally block, so we can call the close or dispose method when the traversal is finished.

The rest of the magic are just implicit conversions between anything which contains def close() : Any or def dispose() : Any and Managed trait.

Enjoy!

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: