Wednesday 22 May 2013

Scala Equality in 30 seconds


  1. In scala == delegages to equals method.

  2.  a == b is equivalent to a equals b
  3. If you want to check referrential equality you call eq method. 

  4.  a eq b is true only if a and b are referrences to the same object
  5. Case classes and Value Classes (2.10) get the equals and hashcode based on class parameters for free.


End of the story!

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!