Spiral Arm Logo

Jono's technical notes

Monday, September 28, 2009

Scala traits to enhance existing java libraries

Recently we moved some code over to Scala which uses Apache's httpClient, through laziness I used

method.getResponseBodyAsString. Apart from being poor form, it breaks our - nothing but errors in the Production logs rule at Spiral Arm.

To alleviate the coding smell we created a trait to read the body as a stream instead of a string. Rather a simple task. The nice things about the trait are the use of the self reference.


self:HttpMethod =>


This means 'I expect to be mixed with something of this type' nicely reducing the scope where the trait can be applied and is also self documenting. We could have returned a None Option instead of an empty String, meh. It's an implementation issue and not a huge issue.


trait SafeResponseBody {


self:HttpMethod =>

def getResponseBodyUpTo(to:Int):String = {

val in = new InputStreamReader(this.getResponseBodyAsStream, "UTF-8")

val buffer = new Array[Char](to)

val n = in.read(buffer,0,to)

n match {

case -1 => ""

case 0 => ""

case _ => new String(buffer, 0, n)

}

}

}


Using the trait is nice and clean, when creating an instance of the particular HttpMethod we mix in our trait and then have access to it's methods.


val method = new PostMethod(url) with SafeResponseBody

...

method.getResponseBodyUpTo(160)


Labels: