<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xebia Blog &#187; Scala</title>
	<atom:link href="http://blog.xebia.com/category/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Easy breezy restful service testing with Dispatch in Scala</title>
		<link>http://blog.xebia.com/2011/11/26/easy-breezy-restful-service-testing-with-dispatch-in-scala/</link>
		<comments>http://blog.xebia.com/2011/11/26/easy-breezy-restful-service-testing-with-dispatch-in-scala/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 00:29:56 +0000</pubDate>
		<dc:creator>Urs Peter</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Uncategorized]]></category>

	<!-- AutoMeta Start -->
	<category>reqbody</category>
	<category>dispatch</category>
	<category>executer</category>
	<category>fromrespstr</category>
	<category>elem</category>
	<category>fromrespxml</category>
	<category>restclienthelper</category>
	<category>handlerverbs</category>
	<category>reqbody</category>
	<category>dispatch</category>
	<category>executer</category>
	<category>fromrespstr</category>
	<category>elem</category>
	<category>fromrespxml</category>
	<category>restclienthelper</category>
	<category>handlerverbs</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=8035</guid>
		<description><![CDATA[For testing a restful service API I was looking for a lean library, which would allow me to test CRUD operations of rest services with as little code as possible. My search led me to Dispatch, which is a highly compact Scala DSL wrapper around Apache’s reliable HttpClient. This DSL, however, is not very well [...]]]></description>
			<content:encoded><![CDATA[<p>For testing a restful service API I was looking for a lean library, which would allow me to test CRUD operations of rest services with as little code as possible. </p>
<p>My search led me to <a href="http://dispatch.databinder.net/Dispatch.html" title="Dispatch">Dispatch</a>, which is a highly compact Scala DSL wrapper around Apache’s reliable <a href="http://hc.apache.org/httpcomponents-client-ga/" title="HttpClient">HttpClient</a>. This DSL, however, is not very well documented and rather hard to decipher due to it&#8217;s heavy usage of symbolic method names but nevertheless highly appealing when understood. </p>
<p>In this blog I&#8217;ll decipher it for you and show how easy it is to test restful services with mere oneliners. </p>
<p><span id="more-8035"></span></p>
<h4>My Prerequisites</h4>
<p>Before we dive into Dispatch’s mysterious DSL let’s look at the prerequisites I had for testing my restful service. These will most likely apply for many other rest services as well:</p>
<ul>
<li>Support for CRUD operations with http’s POST, GET, PUT and DELETE methods</li>
<li>Support for XML and Json as input and output payloads</li>
<li>Support for reading http status codes to test results of erroneous responses like 404 (Not Found)</li>
<li>Support for security aspects such as https and basic/digest authentication</li>
</ul>
<h4>Begin with the End in Mind</h4>
<p>The goal of this blog is it to create a RestClientHelper that offers a set of generic restful client methods and explain how they’re implemented using Dispatch. With these methods in place we will be able to call and therefore test restful service APIs very easily. </p>
<p>The RestClientHelper will be a trait that offers the following client side CRUD methods:</p>
<pre class="brush: scala; title: ; notranslate">
trait RestClientHelper {

  //Create (POST)
  def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T
  def create[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T 

  //Read (GET)
  def query[T](target: String, params: Seq[(String, String)])( fromRespStr: String =&gt; T): (Int, Option[T])
  def query[T](target: String, params: Seq[(String, String)])( fromRespXml: Elem =&gt; T): (Int, Option[T]) 

  //Update (PUT)
  def update[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T
  def update[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T
  def update[T](target: String, reqBody: String): Int
  def update[T](target: String, reqBody: Elem): Int 

  //Delete (DELETE)
  def delete(target: String) :Int
}
</pre>
<p>As you can see, most methods consist of two parameter lists. The first parameter list represents the rest call input such as target uri and request body or parameter map.  The second parameter list is a function that converts the output of a rest service into the desired type. The return type of these methods are of type T, Int or Tuple2[Int, Option[T]]. The Int always represents the http status code, the Option[T] represents the converted output if the service call was successful.  </p>
<h4>How to use the RestClientHelper</h4>
<p>To get an understanding how the RestClientHelper trait is supposed to be used let’s look at an example. Assuming we have a domain object, Person, that provides serialization and deserialization methods for xml a CRUD call sequence with the RestClientHelper trait would look as follows:</p>
<pre class="brush: scala; title: ; notranslate">
val person = Person(&quot;John Doe&quot;)

//POST /add.xml
val p = create(&quot;add.xml&quot;,person.toXml){Person.fromXml(_)}
assert(p.id != None)

//GET /search.xml?q=John+Doe
val (status, personOpt) = query(&quot;search.xml&quot;, Seq(&quot;q&quot; -&gt; &quot;John Doe&quot;)) { Person.fromXml(_) }
assert(status == 200)

//PUT /update.xml
val changedPerson = p.copy(_.name = &quot;John Who&quot;)
val status2  = update(&quot;update.xml&quot;, changedPerson.toXml)
assert(status2 == 200)

//DELETE /delete/4
val status3 = delete(&quot;delete/&quot; + changedPerson.id.get)
assert(status3 == 200)

//GET /search.xml?q=John+Who
1
val (status4, personOpt2) = query(&quot;search.xml&quot;, Seq(&quot;q&quot; -&gt; &quot;John Who&quot;)) { Person.fromXml(_) }
assert(status4 == 404)
assert(personOpt2 == None)
</pre>
<h4>Looking under the hood</h4>
<p>Now let’s dig a little deeper and discover how one of these rest client helper methods are actually implemented using Dispatch.</p>
<pre class="brush: scala; title: ; notranslate">
def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
  executer(:/(host, port) / target &lt;&lt; reqBody &gt;- { fromRespStr })
}
</pre>
<p>Well, this is all that is needed for invoking restful service by means of a POST request. Being new to Dispatch it can help untangling this highly compact DSL for a better understanding.</p>
<p>The core classes participating in an http call as shown above are the following:</p>
<ul>
<li>A <strong><a href="http://databinder.net/dispatch-doc/#dispatch.HttpExecutor" title="HttpExecuter">HttpExecuter (dispatch.HttpExecuter)</a></strong> responsible for executing the http request. A common implementation would be dispatch.Http. In this example it is respresented by the executer object.</li>
<li>A <strong><a href="http://databinder.net/dispatch-doc/#dispatch.Request" title="Request">Request (dispatch.Request)</a></strong>  and its DSL wrapper <a href="http://databinder.net/dispatch-doc/#dispatch.RequestVerbs" title="dispatch.RequestVerbs"><strong>dispatch.RequestVerbs</strong></a>, which are responsible for creating a specific kind of request, e.g.  a gzip http post with content-type application/x-www-form-urlencoded.<br />
The class RequestVerbs contains DSL-ish symbolic methods names, which mostly start with a ‘<’ character indicating that something is ‘added’ to a request (left arrow).<br />
The method << is one of those. It adds a request body to the request and therefore automatically transforms it into a POST request.</li>
<li>A <a href="http://databinder.net/dispatch-doc/#dispatch.Handler" title="dispatch.Handler"><strong>Handler (dispatch.Handler)</strong></a> and its DSL wrapper <a href="http://databinder.net/dispatch-doc/#dispatch.HandlerVerbs" title="dispatch.HandlerVerbs"><strong>dispatch.HandlerVerbs</strong></a>, which is responsible for handling the result returned by the http call, such as converting it to xml or json.<br />
The class HandlerVerbs contains as well DSL-ish symbolic method names, which mostly start with a ‘>’ character indicating that something is done with the ‘output’ of the http call (right arrow).<br />
The method >- is one of those. It converts the response received as a String into the desired type.</li>
<li>For both, the Request and Handler, implicit conversions allows them to be converted into their corresponding DSL wrapper RequestVerbs or HandlerVerbs respectively.</li>
</ul>
<p>With those key classes in mind we can rewrite the above http call in a more verbose manner in order to understand the parts the DSL is made of:</p>
<pre class="brush: scala; title: ; notranslate">
def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    val emptyReq:Request = :/(host, port)

    //implicit conversion applied explicitely
    val reqVerbs:RequestVerbs = Request.toRequestVerbs(emptyReq) 

    val configuredReq:Request = reqVerbs./(target).&lt;&lt;(reqBody)

    //implicit conversion applied explicitely
    val handlerVerbs:HandlerVerbs = Request.toHandlerVerbs(configuredReq)

    //The http executer always needs to be called with a handler
    val handler:Handler[T] = handlerVerbs.&gt;-(fromRespStr)

    executer.apply(handler)
}
</pre>
<p>The executer needs further explanation. As said, Dispatch requires you to use an executer to finally execute an http request. Dispatch offers several types of executers, such as thread and non-thread safe ones. A thread-safe one that makes use of a shared connection pool could be provided as follows:</p>
<pre class="brush: scala; title: ; notranslate">
  protected lazy val executer = new Http with thread.Safety
</pre>
<p>The non-thread counterpart could be accessed like this:</p>
<pre class="brush: scala; title: ; notranslate">
  protected def executer = new Http
</pre>
<p>Various other <a href="http://dispatch.databinder.net/Choose+an+Executor.html" title="executers">executers</a> are available. The ones above will most likely be sufficient for most purposes.</p>
<p>To summarize we can conclude that most of the power of Dispatch from a usage point of view lies within the RequestVerbs and HandlerVerbs classes, which allow us to compose a request and decompose its response the way we want it. There is an excellent <a href="http://www.flotsam.nl/dispatch-periodic-table.html" title="periodic table">periodic table of dispatch operators</a> available that lists all the possible Verb methods with a short description.</p>
<h4>…and now the nitty-gritty details</h4>
<p>With the knowledge we have gained about Dispatch the remaining method implementations of the RestClientHelper should be straight forward.  I’ll show each implementation with a short explanation of the most notable Dispatch methods:</p>
<p><strong>Create (POST) with String in- and output</strong></p>
<pre class="brush: scala; title: ; notranslate">
 def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    executer(:/(host, port).POST /  target &lt;&lt; reqBody &gt;- { fromRespStr })
  }
</pre>
<ul>
<li><i>RequestVars: POST</i><br/>Create a POST request (the POST method is optional because of the &#8216;<<<' method, which forces the request to be a Post)</li>
<li><i>RequestVars: <<(body:String)</i><br/> Post the given String value with text/plain content-type</li>
<li><i>RequestVars: >-[T](block:(String) => T)</i><br/>Convert the response body from a String to the desired type</li>
</ul>
<p><strong>Create (POST) with XML in- and output</strong></p>
<pre class="brush: scala; title: ; notranslate">
  def create[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T = {
    executer(:/(host, port) /  target &lt;&lt; reqBody.toString &lt;&gt; { fromRespXml })
  }
</pre>
<ul>
<li><i>RequestVerbs: <<(body:String)</i><br/>Post the given String value with text/plain content-type</li>
<li><i>HandlerVerbs: <>[T](block:(Elem) => T)</i><br/>Convert the response body from an Elem to the desired type</li>
</ul>
<p><strong>Read (GET)</strong><br />
The read method is probably the most intriguing one from the whole series. In order to understand it fully, I will provide a detailed explanation:</p>
<pre class="brush: scala; title: ; notranslate">
 def query[T](target: String, params: Seq[(String, String)])(fromRespStr: String =&gt; T): (Int, Option[T]) = {
    executer x (:/(host, port) /  target &lt;&lt;? params &gt;:&gt; identity) {
      case (200, _, Some(entity), _) =&gt; {
     	   val respBodyStr = fromInputStream(entity.getContent()).getLines.mkString
           (200, Some(fromRespStr(respBodyStr)))
      }
      case (status, _, _, _) =&gt; (status, None)
    }
 }
</pre>
<p>Now let’s look at the most important Dispatch ingredients for this GET request:</p>
<p><u>Input processing</u><br />
The method &lt;&lt;? from RequestVerbs: &lt;&lt;?(params:Traversable[(String, String)]) simply adds query parameters to the request url.</p>
<p><u>Output processing</u><br />
To process the query result we are interested in two things: the response code and response body. Both are returned in the form of a Tuple2 (Int, Option[T]), where Int represents the status code and Option[T] the converted object in case the query yielded a result. The question is how can we retrieve both of them, since Dispatch does not offer a symbolic method that does that for us. </p>
<p>First let’s take a closer look at what is actually called: Instead of providing the executer with a handler directly we use the method ‘x’. </p>
<pre class="brush: scala; title: ; notranslate">
  executer x (…)
</pre>
<p>Why is that? By calling the executer’s apply method (that’s what finally happens under the hood) the handler block is only called in case the response status code is 200 – 204. In all other cases an Exception is thrown. So if we want to intercept all response codes we need to use the Executer’s x[T](hanlder:Handler[T]) method, which executes the handler no matter which response code is returned. </p>
<p>The next question is what kind of handler is passed to the executer’s x method? If we explicitly assigned the first part of the DSL construct to a handler it would look as follows:</p>
<pre class="brush: scala; title: ; notranslate">
  val intermediateHandler = (:/(host, port) /  target &lt;&lt;? params &gt;:&gt; identity)
</pre>
<p>The ‘magic’ lies in the >:> identity construct. According to the API the HandlerVerb method >:> accepts a function, by which the response headers can be processed. By passing Scala’s Predef identity method to the >:> method, nothing is processed but the resulting handler of type Handler[Map[String, Set[String]]] is returned.</p>
<p>As said, the handler above does not process the result itself. The real processing is done by the case statements, which are the last arguments that are passed to the DSL construct. How do we need to interpret that? For a better understanding, the last statement could be rewritten as follows:</p>
<pre class="brush: scala; title: ; notranslate">
 val realHandler = intermediateHandler.apply {
    case (200, _, Some(entity), _) =&gt; {
       val respBodyStr = fromInputStream(entity.getContent()).getLines.mkString
       (200, Some(fromRespStr(respBodyStr)))
    }
    case (status, _, _, _) =&gt; (status, None)
 }
 executer.x(realHandler)
</pre>
<p>What happens is that we construct another handler by calling the apply method of the previously created one. The apply method of all the handlers accept a function with the following signature:</p>
<pre class="brush: scala; title: ; notranslate">
    apply(next:(Int, HttpResponse, Option[HttpEntity], () =&gt; T) =&gt; R)
</pre>
<p>The Int stands for the response code, the HttpResponse and Option[HttpEntity] give us access to the underlying Apache HttpClient implementation and the argument () => T represents the transformation function, which transforms the response to type T, the type of the Handler itself.</p>
<p>As you probably know a case statement IS a function (PartialFunction), which can be chained and passed &#8211; even if chained &#8211; as a single PartialFunction to a method. So by providing the handler’s apply method with the above case statements we’re able to define in detail how the low-level result of the http call needs to be processed. In our case this means: retrieve and convert the response body when the response code is 200, otherwise simply return the response code. </p>
<p>Even though this construct might look rather complicated it is a very powerful way to access and process the raw result that the http call returns. </p>
<p><strong>Update (PUT) with String in- and output</strong></p>
<pre class="brush: scala; title: ; notranslate">
def update[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
  executer(:/(host, port).PUT /  target &lt;&lt;&lt; reqBody &gt;- { fromRespStr })
}
</pre>
<ul>
<li><i>RequestVerbs: PUT</i><br/>Create a PUT request (the PUT method is optional because the <<< method forces the request to be a PUT)</li>
<li><i>RequestVerbs: <<<(body:String)</i><br/>Put the given String value with text/plain content-type</li>
<li><i>HandlerVerbs: >-[T](block:(String) => T)</i><br/>Convert the response body from a String to the desired type</li>
</ul>
<p><strong>Update (PUT) with XML in- and output</strong></p>
<pre class="brush: scala; title: ; notranslate">
 def update[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T = {
  executer(:/(host, port) /  target &lt;&lt;&lt; reqBody.toString &lt;&gt; { fromRespXml })
 }
</pre>
<ul>
<li><i>RequestVerbs: <<<(body:String)</i><br/>Put the given String value with text/plain content-type </li>
<li><i>HandlerVerbs: <>[T](block:(Elem) => T)</i><br/>Convert the response body from an Elem to the desired type</li>
</ul>
<p><strong>Update (PUT) without response body</strong></p>
<pre class="brush: scala; title: ; notranslate">
def update[T](target: String, reqBody: String): Int = {
    executer x ((:/(host, port) /  target &lt;&lt;&lt; reqBody &gt;:&gt; identity) {
      case (status, _, _, _) =&gt; status
    })
}
</pre>
<p>If we want to send a PUT without expecting a response body but are still interested in the response code we use the same construct as described above in the read sample. The only difference compared to the read example is that we do not retrieve the response body, but simply return the response code.</p>
<p><strong>Delete (DELETE)</strong></p>
<pre class="brush: scala; title: ; notranslate">
def delete(target: String):Int = {
   executer x ((:/(host, port)).DELETE /  target &gt;:&gt; identity)  {
      case (status, _, _, _) =&gt; status
   }
}
</pre>
<p>The delete method does not process a response body. In order to know whether the deletion was successful we are however interested in the response code. Therefore, we again use the construct as in the read example.</p>
<h4>Security &#038; Authentication</h4>
<p>Finally, let’s explain what we needed to do if our restful service was secured with https and/or basic/digest authentication. </p>
<p>For https the RequestVars&#8217; secure method should be called on the request, for authentication the as(“username”, “pwd”) method. Therefore, a secure create (POST) call that uses basic authentication would look as follows:</p>
<pre class="brush: scala; title: ; notranslate">
 def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    executer(:/(host, port).secure.as(“user”, “pwd”) /  target &lt;&lt; reqBody &gt;- { fromRespStr })
 }
</pre>
<p>In case security combined with authentication is used it is self evident that the RestClientHelper trait would provide a method that returns a preconfigured request in order to by DRY:</p>
<pre class="brush: scala; title: ; notranslate">
trait RestClientHelper {
 val host: String
 val port: Int
 protected def username:String = &quot;unkown&quot;
 protected def pwd:String = &quot;unkown&quot;
 private def req = :/(host, port).secure.as(username, pwd)

 def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    http(req / target &lt;&lt; reqBody &gt;- { fromRespStr })
 }
...
</pre>
<h4>Wait, there is more</h4>
<p>Dispatch offers various other features that are not mentioned in this blog. E.g.: Dispatch can directly convert a response body into a Lift Json object by means of the ># method (a good <a href="http://dispatch.databinder.net/Lift+JSON.html" title="Lift+JSON">example</a> is provided on the Dispatch site), it can execute http requests in a background thread, there are various HandlerVerbs and RequestVers, which we have not covered yet like using gzip mode, chaining handlers etc. to mention some of them. (check the <a href="http://www.flotsam.nl/dispatch-periodic-table.html" title="periodic table">periodic table</a> for further reference). For testing restful services however, the stuff covered in this blog should suffice.</p>
<h4>The RestClientHelper ready to use</h4>
<p>To conclude this blog as follows the source of the RestClientHelper trait, which hopefully makes restful service testing for you a piece of cake and fun (<a href="http://dispatch.databinder.net/Project+Setup.html" title="Setup">after having Dispatch set up</a>)!</p>
<pre class="brush: scala; title: ; notranslate">
import scala.io.Source._
import scala.xml._
import org.apache.http._
import dispatch._

trait RestClientHelper {
  val host: String
  val port: Int
  val contextRoot: String
  protected val ssl = false
  protected val username = &quot;notdefined&quot;
  protected val pwd = &quot;notdefined&quot;
  protected val executer = new Http with thread.Safety
  private def req = {
    val req = :/(host, port).as(username, pwd) / contextRoot
    if (ssl) req.secure else req
  }

  def query[T](target: String, params: Seq[(String, String)])(fromRespStr: String =&gt; T): (Int, Option[T]) = {
    executer x (req / target &lt;&lt;? params &gt;:&gt; identity) {
      case (200, _, Some(entity), _) =&gt; {
        val respStr = fromInputStream(entity.getContent()).getLines.mkString
        (200, Some(fromRespStr(respStr)))
      }
      case (status, _, _, _) =&gt; (status, None)
    }
  }
  def query[T](target: String)(fromRespStr: String =&gt; T): (Int, Option[T]) = {
    query(target, List())(fromRespStr)
  }
  def queryXml[T](target: String)(fromRespXml: Elem =&gt; T): (Int, Option[T]) = {
    queryXml(target, List())(fromRespXml)
  }
  def queryXml[T](target: String, params: Seq[(String, String)])(fromRespXml: Elem =&gt; T): (Int, Option[T]) = {
    val convertOutput = (s: String) =&gt; fromRespXml(XML.loadString(s))
    query(target, params)(convertOutput(_))
  }

  def create[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    executer(req / target &lt;&lt; reqBody &gt;- { fromRespStr })
  }
  def create[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T = {
    executer(req / target &lt;&lt; reqBody.toString &lt;&gt; { fromRespXml })
  }

  def update[T](target: String, reqBody: String)(fromRespStr: String =&gt; T): T = {
    executer(req / target &lt;&lt;&lt; reqBody &gt;- { fromRespStr })
  }
  def update[T](target: String, reqBody: Elem)(fromRespXml: Elem =&gt; T): T = {
    executer(req / target &lt;&lt;&lt; reqBody.toString &lt;&gt; { fromRespXml })
  }
  def update[T](target: String, reqBody: String): Int = {
    executer x ((req / target &lt;&lt;&lt; reqBody &gt;:&gt; identity) {
      case (status, _, _, _) =&gt; status
    })
  }
  def update[T](target: String, reqBody: Elem): Int = {
    update(target, reqBody.toString)
  }

  def delete(target: String): Int = {
    executer x ((req).DELETE / target &gt;:&gt; identity) {
      case (status, _, _, _) =&gt; status
    }
  }
}
</pre>
<p>Possible usage in an object or any other class you want the RestClientHelper to be mixed in:</p>
<pre class="brush: scala; title: ; notranslate">
object MyRestClientHelper extends RestClientHelper {
    val host = &quot;rest.service.host&quot;
    val port = 443
    val contextRoot = &quot;v1&quot;
    override val ssl = true
    override val username = &quot;myusername&quot;
    override val pwd = &quot;secret&quot;
}
</pre>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/11/26/easy-breezy-restful-service-testing-with-dispatch-in-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F11%2F26%2Feasy-breezy-restful-service-testing-with-dispatch-in-scala%2F&amp;title=Easy%20breezy%20restful%20service%20testing%20with%20Dispatch%20in%20Scala" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/11/26/easy-breezy-restful-service-testing-with-dispatch-in-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting the Java out of your Scala, part 2</title>
		<link>http://blog.xebia.com/2011/11/12/getting-the-java-out-of-your-scala-part-2/</link>
		<comments>http://blog.xebia.com/2011/11/12/getting-the-java-out-of-your-scala-part-2/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 17:09:36 +0000</pubDate>
		<dc:creator>Jan Vermeir</dc:creator>
				<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category>stuffs</category>
	<category>groupedbylabel</category>
	<category>groupby</category>
	<category>expectedresult</category>
	<category>mapvalues</category>
	<category>currenthead</category>
	<category>shoppinglist</category>
	<category>resultgroupedbylabel</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7998</guid>
		<description><![CDATA[Getting the Java out of your Scala, part 2 I’m still trying to get rid of old habits, to shake of my winter hide, so to speak, and create some real Scala in stead of ScaVa (i.e. Java with a Scala syntax). If you’re interested you can bear witness to my struggle on GitHub (ShoppingList [...]]]></description>
			<content:encoded><![CDATA[<p>Getting the Java out of your Scala, part 2</p>
<p>I’m still trying to get rid of old habits, to shake of my winter hide, so to speak, and create some real Scala in stead of ScaVa (i.e. Java with a Scala syntax). If you’re interested you can bear witness to my struggle on GitHub (<a href='https://github.com/jvermeir/ShoppingList'>ShoppingList on GitHub</a>). This story came about because I asked some colleagues for help. We ended up rewriting loops in several ways.<br />
What I’ll show you is some alternatives to classic loops over collections.<br />
<span id="more-7998"></span></p>
<p>The code <a href='http://blog.xebia.com/wp-content/uploads/2011/11/SumByGroup.txt'>is attached here</a>. The example shows how to summarize items in a list. The objects in the list are all instances of class Stuff, a simple value container for a String and an Int. The idea is to summarize Stuffs with the same key to produce a new list:</p>
<pre class="brush: scala; title: ; notranslate">
  val items = List(Stuff(&quot;A&quot;, 1), Stuff(&quot;A&quot;, 2), Stuff(&quot;B&quot;, 3), Stuff(&quot;B&quot;, 4))
</pre>
<p>should become</p>
<pre class="brush: scala; title: ; notranslate">
  val expectedResult = List(Stuff(&quot;A&quot;, 3), Stuff(&quot;B&quot;, 7))
</pre>
<p>where Stuff is a simple case class with two attributes:</p>
<pre class="brush: scala; title: ; notranslate">
case class Stuff(val label: String, val number: Int)
</pre>
<p>Because I’m a long time Java programmer, my first solution looks like this:</p>
<pre class="brush: scala; title: ; notranslate">
  def classicSum = {
    var result: List[Stuff] = List()
    for (item &lt;- items) {
      if (result.size &gt; 0 &amp;&amp; item.label == result.head.label) {
        result = Stuff(result.head.label, result.head.number + item.number) :: result.drop(1)
      } else {
        result = item :: result
      }
    }
    assertEquals(expectedResult, result.reverse)
  }
 </pre>
<p>Good old looping and a var to collect the result. This works, but it doesn’t say what’s happening. All you see is a loop and some fancy list processing. Note the call to drop(1) allowing you to replace the head of the list with a new instance. I like the drop function and I’ve used it in other programs but here it just obfuscates matters.</p>
<p>The next solution is to go recursive. If you check out the version of ShoppingList as of October/November 2011, you’ll find lots of recursion. My goal at the time was to jam recursion into my head by banning all other forms of looping.<br />
Applied to the list of Stuff instances and the problem at hand, the result is tragic:</p>
<pre class="brush: scala; title: ; notranslate">
  def recursiveSum = {
    @tailrec def sum(listOfPairs: List[Stuff], result: List[Stuff]): List[Stuff] = {
      listOfPairs match {
        case Nil =&gt; result
        case head :: tail =&gt;
          {
            val currentHead = if (result.size == 0) { Stuff(head.label, 0) } else { result.head }
            val newResult =
              if (currentHead.label == head.label) {
                Stuff(currentHead.label, currentHead.number + head.number) :: result.drop(1)
              } else { head :: result }
            sum(tail, newResult)
          }
      }
    }
    val result = sum(items, List())
    assertEquals(expectedResult, result.reverse)
  }
 </pre>
<p>My next version leverages Scala’s collections to drastically reduce the amount of code. The first attempt passes the test but it is cryptic. In the spirit of the red-green-refactor mantra I’ll show it to you anyway:</p>
<pre class="brush: scala; title: ; notranslate">
  def sumByGroupSolution1 = {
    val groupedByLabel = items.groupBy(_.label)
    val result = groupedByLabel map { t =&gt; Stuff(t._1, t._2 map { _.number } sum) }
    assertEquals(expectedResult, result)
  }
 </pre>
<p>There! Go and parse that if you need to change this code sometime next year (note: having worked with this code for some time now while writing this blog, I must admit that it grows on you; after a while it doesn’t hurt all that much, sort of like a new pair of shoes). This cryptic piece of mal-ware illustrates the use of three powerfull methods named groupBy, map and sum.<br />
groupBy is in a sense comparable to SQLs group by clause. The Scala version takes a collection and returns a Map. The map’s key is the element used to group by (Stuff.label in my case). The value is a List of elements that have the same key. In this case the items collection contains Stuff instances. I’ve grouped by the label field so the type of groupedByLabel is Map[String, List[Stuff]]. On this Map we have to apply a sum function to add up all Stuff instances in the List of Stuffs. Sum however works on Int’s, so before sum can be applied we have to extract the number field of each Stuff instance. This is done by a map: map {_.number}. The mapping is applied to each Stuff instance in the list of Stuffs that was returned by groupedByLabel. </p>
<p>By factoring out part of the code on line 3 in the example above, we can improve readability: </p>
<pre class="brush: scala; title: ; notranslate">
  def sumByGroupSolution2 = {
	val stuffsGroupedByLabel = items.groupBy(_.label)
    def sumOfStuffsWithTheSameLabel(stuffs: List[Stuff]): Int = stuffs map { _.number } sum
    val result = stuffsGroupedByLabel map { t =&gt; Stuff(t._1, sumOfStuffsWithTheSameLabel(t._2)) }
    assertEquals(expectedResult, result)
  }
 </pre>
<p>I think this is better because now the result of part of the computation is named. Naming a thing makes it easier to see the algorithm.</p>
<p>The next solution uses more intermediate results. The results of each map or sum operation are stored in a variable that gets a meaningful name. This clarifies the meaning of intermediate results but the amount of code grows.</p>
<pre class="brush: scala; title: ; notranslate">
  @Test
  def sumByGroupSolution5 = {
    val calcSumOfStuff = (stuffs: Seq[Stuff]) =&gt; stuffs map { _.number } sum
    val groupedByLabel = items.groupBy { _.label }
    val resultGroupedByLabel = groupedByLabel mapValues { calcSumOfStuff }
    val result = resultGroupedByLabel map { t =&gt; Stuff(t._1, t._2) }
    assertEquals(expectedResult, result)
  }
</pre>
<p>The code shows another Map function named mapValues. </p>
<pre class="brush: scala; title: ; notranslate">
 val resultGroupedByLabel = groupedByLabel mapValues { calcSumOfStuff }
</pre>
<p>mapValues works on the values of a map only, ignoring the keys. In my case the keys don’t really matter (they’re an artifact of the groupBy call) so I can get away with mapValues rather than map.</p>
<p>Naming things was also the inspiration for the next solution. Now I’m not extracting intermediate results but in this case I’ve named the variables being manipulated:</p>
<pre class="brush: scala; title: ; notranslate">
  def sumByGroupSolution4 = {
    val groupedByLabel = items.groupBy(_.label)
    val result = groupedByLabel map { case (label, stuffs) =&gt; Stuff(label, stuffs map { _.number } sum) }
    assertEquals(expectedResult, result)
  }
</pre>
<p>The case statement as argument to the map makes it possible to introduce two variables to identify the things we’re manipulating. Label and stuffs mean more to me than _1 and _2. </p>
<p>Looking back on my struggle I like this solution best. I think it is both concise and easy to read. </p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/11/12/getting-the-java-out-of-your-scala-part-2/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F11%2F12%2Fgetting-the-java-out-of-your-scala-part-2%2F&amp;title=Getting%20the%20Java%20out%20of%20your%20Scala%2C%20part%202" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/11/12/getting-the-java-out-of-your-scala-part-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Comparing Apples to Pears in Scala &#8211; or Abstract Types to the Rescue</title>
		<link>http://blog.xebia.com/2011/08/17/comparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue/</link>
		<comments>http://blog.xebia.com/2011/08/17/comparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 19:57:38 +0000</pubDate>
		<dc:creator>Urs Peter</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Uncategorized]]></category>

	<!-- AutoMeta Start -->
	<category>euro</category>
	<category>currency</category>
	<category>dollar</category>
	<category>orderedmoney</category>
	<category>currencies</category>
	<category>apples</category>
	<category>implicit</category>
	<category>double</category>
	<category>euro</category>
	<category>currency</category>
	<category>dollar</category>
	<category>orderedmoney</category>
	<category>currencies</category>
	<category>apples</category>
	<category>implicit</category>
	<category>double</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7289</guid>
		<description><![CDATA[Abstract types in Scala can make your life much easier. In this blog I’m going to recap my intellectual journey to compare &#8216;apples to pears&#8217; in a typesafe manner, which led me to abstract types. My quest was to write code, which enables me to compare different kinds of currencies as elegant as possible. What [...]]]></description>
			<content:encoded><![CDATA[<p>Abstract types in Scala can make your life much easier. In this blog I’m going to recap my intellectual journey to compare &#8216;apples to pears&#8217; in a typesafe manner, which led me to abstract types. </p>
<p><span id="more-7289"></span></p>
<p>My quest was to write code, which enables me to compare different kinds of currencies as elegant as possible. What I wanted was a very simple DSL with which I could do the following:</p>
<pre class="brush: scala; title: ; notranslate">2.dollar &gt; 1.euro</pre>
<h4>The very beginning</h4>
<p>That’s where I started out: </p>
<pre class="brush: scala; title: ; notranslate">
trait Money extends Ordered[Money] {
   val unit:String
   val amount:Double
   def compare(that:Money) = if(amount &gt; that.amount) 1 else -1
}

case class Euro(amount: Double) with Money {
    val unit = “EUR”
}

case class Dollar(amount:Double) with Money {
    val unit = “USD”
}
</pre>
<p>You probably see already which problem we’ll encounter. When we want to compare the same currencies this code will work fine. However, comparing two different kinds of currencies will compile but will yield a wrong result:</p>
<pre class="brush: scala; title: ; notranslate">
//works as expected
assert(Euro(200) &gt; Euro(100))

//compiles but yields wrong result
assert(Euro(99) &gt; Dollar(100))
</pre>
<p>So my question was how to cope with this situation. Having a trait Money that does the comparison is definitely not the way to go because it does not take the conversion of currencies into considering. This design allows me to compare Euros with Dollars whereas we’re only comparing amounts. </p>
<h4>No real option for the problem</h4>
<p>One second I considered to add the following check to the Money’s compare method:</p>
<pre class="brush: scala; title: ; notranslate">def compare(that:Money) = {
    require(unit == that.unit)
    if(amount &gt; that.amount) 1 else -1
}</pre>
<p>Needless to say that this cannot be considered a viable solution. Especially with regard to Scala’s rich type system, which should help you to exactly solve such problems. So how to cope with it?</p>
<h4>Abstract types to the rescue</h4>
<p>Minutes later I remembered abstract types, which provided the solution I was exactly looking for. Instead of letting the compare method accept a type of Money, I define an abstract type alias called Currency, which extends from Money. This abstract type is then used as input for the compare method.</p>
<pre class="brush: scala; title: ; notranslate">trait Money  {
  type Currency &lt;: Money
  val unit: String
  val amount: Double
  def compare(that:Currency):Int = if(amount &gt; that.amount) 1 else -1
} </pre>
<p>Next I can define an OrderedMoney trait in order to introduce the Ordered trait, for which the compare method is needed in the first place.</p>
<pre class="brush: scala; title: ; notranslate">
trait OrderedMoney[T &lt;: Money] extends Money with Ordered[T]
</pre>
<p>Because the super trait, Money, already contains an implementation of the compare method the OrderedMoney trait does not need to implement it. Obviously, we also could have provided the implementation of the compare method in the OrderedMoney trait. However the effect is the same.</p>
<p>The OrderedMoney trait needs to be mixed in for every concrete currency implementation as follows:</p>
<pre class="brush: scala; title: ; notranslate">
case class Euro(val amount: Double) extends OrderedMoney[Euro]{
  type Currency = Euro
  val unit = &quot;EUR&quot;
}

case class Dollar(val amount: Double) extends OrderedMoney[Dollar]{
  type Currency = Dollar
  val unit = &quot;USD&quot;
}
</pre>
<p>From this point on the compiler makes sure that I only compare apples to apples and not apples to pears:</p>
<pre class="brush: scala; title: ; notranslate">
//works as expected
assert(Euro(200) &gt; Euro(100))

//does not compile anymore, as intended
assert(Dollar(100) &gt; Euro(100))
scala: Diverging implicit conversion…</pre>
<h4>Making it compare apples to pears</h4>
<p>In the end we would like to compare apples to pears or here Dollars to Euros. In order to achieve that we simply have to add some implicit conversion logic and our money DSL is (nearly) complete:</p>
<pre class="brush: scala; title: ; notranslate">object Conversions {
  implicit def fromEuroToDollar(d: Euro) = new Dollar(d.amount * 1.2)
  implicit def fromDollarToEuro(d: Dollar) = new Euro(d.amount * 0.85)
}</pre>
<p>For the sake of simplicity we use a hard-coded value to convert from one currency to another. Ideally such functionality would have to be placed in a separate class, like a CurrencyConverter. With these conversions in place apples can finally be compared to pears:</p>
<pre class="brush: scala; title: ; notranslate">//works as expected
assert(Euro(200) &gt; Euro(100))

//compiles AND works as expected
assert(Dollar(100) &gt; Euro(100))</pre>
<h4>Finishing touch</h4>
<p>For a user of this API it would be convenient to use natural syntax like 2.euro instead of Euro(2). For this to happen only another simple piece of conversion logic needs to be added:</p>
<pre class="brush: scala; title: ; notranslate">object Conversions {
...
implicit def fromDoubleToCurrency(d: Double) = new {
    def euro =  Euro(d)
    def dollar = Dollar(d)
  }
}</pre>
<p>This implicit method converts a Double into an anonymous object that contains a euro and a dollar method. With this in place every Double is pimped with these methods, which makes this DSL as smooth to use as initially intended:</p>
<pre class="brush: scala; title: ; notranslate">2.euro &gt; 2.dollar</pre>
<h4>Round up: Adding basic arithmetic operations</h4>
<p>Are we there yet? Well, we came quite far but it would be nice if we were able to calculate with currencies, preferably with different types of currencies. The following operations would be quite useful:</p>
<pre class="brush: scala; title: ; notranslate">//calculate with same types of currencies
2.euro + 10.euro 

//calculations with different types of currencies
1.euro + 20.dollar – 5.pounds</pre>
<p>The question is how to implement this requirement with as little impact as possible.  With some lines of code this additional requirement can be satisfied quite easily:</p>
<pre class="brush: scala; title: ; notranslate">
trait Money  {
  ...
  def create(amount:Double):Currency
  def +(that:Currency) = create(amount + that.amount)
  def -(that:Currency) = create(amount - that.amount)
}</pre>
<p>We&#8217;ve added a + and &#8211; method to Money and an abstract create method, which is needed to instantiate a currency with the calculated amount. For every type of currency the only thing we have to do is implementing the create method as follows:</p>
<pre class="brush: scala; title: ; notranslate">case class Euro(val amount: Double) extends OrderedMoney[Euro]{
  type Currency = Euro
  val unit = &quot;EUR&quot;
  def create(amount:Double) = Euro(amount)
}</pre>
<p>And from then on we not only can compare different currencies but also calculate with them:</p>
<pre class="brush: scala; title: ; notranslate">//calculations and comparisons with different types of currencies
1.euro + 20.euro &gt; 15.dollar – 3.euro</pre>
<h4>All at once</h4>
<p>So to round up here the whole code, which enables you to compare apples to pears and perform some basic arithmetic operations all in a typesafe way:</p>
<pre class="brush: scala; title: ; notranslate">
trait Money  {
  type Currency &lt;: Money
  val unit: String
  val amount: Double
  def compare(that:Currency):Int =  if(amount &gt; that.amount) 1 else -1
  def +(that:Currency) = create(amount + that.amount)
  def -(that:Currency) = create(amount - that.amount)
  protected def create(amount:Double):Currency
}

trait OrderedMoney[T &lt;: Money] extends Money with Ordered[T] 

case class Euro(amount: Double) extends OrderedMoney[Euro]{
  type Currency = Euro
  val unit = &quot;EUR&quot;
  def create(amount:Double) = Euro(amount)
}

case class Dollar(amount: Double) extends OrderedMoney[Dollar]{
  type Currency = Dollar
  val unit = &quot;USD&quot;
  def create(amount:Double) = Dollar(amount)
}

object Conversions {
  implicit def fromEuroToDollar(d: Euro) =  Dollar(d.amount * 1.2)
  implicit def fromDollarToEuro(d: Dollar) = Euro(d.amount * 0.85)
  implicit def fromDoubleToCurrency(d: Double) = new {
    def euro =  Euro(d)
    def dollar = Dollar(d)
  }
}

//usage samples:
assert(2.dollar + 3.euro &gt;= 1.dollar + 1.dollar + 1.euro)
</pre>
<p>After writing this code, I finally understood why Martin Odersky ‘s new company was baptized ‘typesafe’ : that’s what Scala for a &#8216;big part&#8217; is &#8216;all&#8217;  about <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />   </p>
<h3>Acknowledgments</h3>
<p>This blog was partly inspired on an example in the book <a href="http://www.artima.com/pins1ed/abstract-members.html#20.9">Programming in Scala, Chapter 20, Case study currencies</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/08/17/comparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F08%2F17%2Fcomparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue%2F&amp;title=Comparing%20Apples%20to%20Pears%20in%20Scala%20%26%238211%3B%20or%20Abstract%20Types%20to%20the%20Rescue" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/08/17/comparing-apples-to-pears-in-scala-or-abstract-types-to-the-rescue/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Scala ORM with Squeryl &#8211; A simple getting started guide</title>
		<link>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/</link>
		<comments>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 16:46:02 +0000</pubDate>
		<dc:creator>Jeroen van Wilgenburg</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[sbt]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[squeryl]]></category>

	<!-- AutoMeta Start -->
	<category>squeryl</category>
	<category>movies</category>
	<category>movies</category>
	<category>squeryl_sbt_minimal_example</category>
	<category>intransaction</category>
	<category>scweery</category>
	<category>movie</category>
	<category>postgresql</category>
	<category>squeryl</category>
	<category>movies</category>
	<category>movies</category>
	<category>squeryl_sbt_minimal_example</category>
	<category>intransaction</category>
	<category>scweery</category>
	<category>movie</category>
	<category>postgresql</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=7023</guid>
		<description><![CDATA[Since my pet project (I will eventually blog about that) is in desperate need of a database and I&#8217;m doing enough Java on my day job I decided to give a Scala ORM framework a shot. I have to warn you that I&#8217;m kind of a Scala hacker. I abuse it like a scripting language [...]]]></description>
			<content:encoded><![CDATA[<p>Since my pet project (I will eventually blog about that) is in desperate need of a database and I&#8217;m doing enough Java on my day job I decided to give a Scala ORM framework a shot.<br />
I have to warn you that I&#8217;m kind of a Scala hacker. I abuse it like a scripting language and usually grab some examples, put them together and wait for my colleagues to say &#8220;You don&#8217;t want that&#8221; or &#8220;You&#8217;re doing it wrong&#8221;. So don&#8217;t hesitate to correct me, maybe I&#8217;ll learn something too <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><span id="more-7023"></span></p>
<h2>Picking the right ORM-framework</h2>
<p>I didn&#8217;t do any extensive research, just some googling. A framework called Scweery popped up. The name <a href="http://twitter.com/#!/scweery" target="_blank">Scweery</a> sounded very nice and it has a Twitter account with a funny avatar, so why look any further? Well, it seems the project isn&#8217;t that active anymore (no updates for over a year and that&#8217;s a long time with Scala).<br />
Finally Stackoverflow came to the rescue. I found a question called <a href="http://stackoverflow.com/questions/1362748/wanted-good-examples-of-scala-database-persistence" target="_blank">Examples of Scala database persistence</a> . I picked <a href="http://squeryl.org" target="_blank">Squeryl</a>, the syntax looked nice and there was useful documentation. I&#8217;m not sure whether I picked the right framework, but it survived my initial selection, so let&#8217;s find out.</p>
<h2>Setting up the environment</h2>
<p>For this article I assume the following:</p>
<p>-You have version 2.9.0 of <a href="http://www.scala-lang.org/downloads" target="_blank">Scala</a> installed<br />
-<a href="http://git-scm.com/" target="_blank">Git</a> is on your system<br />
-<a href="https://github.com/harrah/xsbt/wiki/Setup" target="_blank">SBT</a> is available on the command line (I used version 0.7.7)</p>
<p>I believe the links above explain everything pretty well, so let&#8217;s get started!</p>
<h2>Getting started</h2>
<p>I used the &#8216;minimal example&#8217; project to get started:</p>
<pre class="brush: bash; title: ; notranslate">
git clone https://github.com/pbrant/squeryl_sbt_minimal_example
cd squeryl_sbt_minimal_example
squeryl_sbt_minimal_example&gt;sbt
....
[info]    using ExampleProject with sbt 0.7.7 and Scala 2.9.0
squeryl_sbt_minimal_example&gt;update
.....
squeryl_sbt_minimal_example&gt;compile
squeryl_sbt_minimal_example&gt;run
</pre>
<p>I updated the Scala version to 2.9.0. This can be done by changing the version number project/build/build.properties. For this article it doesn&#8217;t matter much, but for your real project this newer version has lots of improvements.</p>
<p>That went pretty smooth. Let&#8217;s rip everything out and use Postgres. Open the file Main.scala (/src/main/scala/code). First remove drop, create and printDdl. We don&#8217;t want our valuable production database to be destroyed!<br />
For my database testing I use my good old movie database. With ancient column names (in Dutch) and the ID column is a String. This might sound like a bad idea, but real databases are like this and I found out it&#8217;s a good way to test a new framework.</p>
<h3>Schema definition</h3>
<p>The first section to change is Library extends Schema. This is the section where the tables are defined. My table is called movies.</p>
<pre class="brush: scala; title: ; notranslate">
val movies = table[Movies]
</pre>
<p>When running the example (with some additional code, so don&#8217;t try it yet) I got the following error:<br />
org.postgresql.util.PSQLException: ERROR: relation &#8220;Movies&#8221; does not exist</p>
<p>It seems the queries are executed with the table names surrounded with double quotes, which means case sensitive. To solve this append (&#8220;MOVIES&#8221;) to the table definition. Now we can also solve the problem that a class is singular (unlike a database table). Now I can call the class Movie instead of Movies:</p>
<pre class="brush: scala; title: ; notranslate">
val movies = table[Movie](&quot;MOVIES&quot;)
</pre>
<h3>Table definition</h3>
<p>Our next step is the table definition. (In Dutch, &#8220;jaar&#8221; means &#8220;year&#8221; and &#8220;naam&#8221; means &#8220;name&#8221;) This time we have to use annotations to use other column names (to get rid of typos and underscores):</p>
<pre class="brush: scala; title: ; notranslate">
class Movie(
 @Column(&quot;imdb_id&quot;)
 val imdbId: String,
 @Column(&quot;jaar&quot;)
 val year: Int,
 @Column(&quot;naam_film&quot;)
 val name: String,
 @Column(&quot;genre&quot;)
 val genres: String
)
</pre>
<p>Note that I used val for the columns, when the columns are mutable it&#8217;s allowed to use var.</p>
<h3>Connecting to Postgresql</h3>
<p>To connect to to a Postgres database replace the H2 dependency in /project/build/ExampleProject.scala with</p>
<pre class="brush: scala; title: ; notranslate">
val pg = &quot;postgresql&quot; % &quot;postgresql&quot; % &quot;9.0-801.jdbc4&quot;
</pre>
<p>Now go to the main method in Main.scala and replace the driver and connection parameters:</p>
<pre class="brush: scala; title: ; notranslate">
Class.forName(&quot;org.postgresql.Driver&quot;);
SessionFactory.concreteFactory = Some(() =&gt;
 Session.create(
 java.sql.DriverManager.getConnection(&quot;jdbc:postgresql://localhost/moviedb&quot;, &quot;bill&quot;, &quot;s3cr3tp455w0rdth4t15nt5053cr3t4nym0r3n0w&quot;),
 new PostgreSqlAdapter)
)
</pre>
<p>At a first glance it just looks like JDBC, but the Some(()=&gt;..) notation might be a bit odd. This is by-name-parameter, just see it as a function that creates a session whenever needed.</p>
<h3>A select * from</h3>
<p>The final section is doing the actual query:</p>
<pre class="brush: scala; title: ; notranslate">
inTransaction {
 val movies = from(Library.movie)(select(_))
 for (movie &lt;- movies){
 println (movie.name)
 }
}
</pre>
<p>To execute queries you need a transaction (also for read only queries). A transaction is available after the initialization of the SessionFactory.concreteFactory. To run code in a transaction wrap it in an inTransaction block (you can also use &#8216;transaction&#8217;, this always starts a new transaction, inTransaction only does when there is no transaction in progress).</p>
<p>The first line in the inTransaction block does a select * from movie.</p>
<p>Scala might be a bit confusing when you&#8217;re new to it, like me. The scaladocs might help. From can be found <a href="http://squeryl.org/api/org/squeryl/dsl/boilerplate/FromSignatures.html" target="_blank">here</a> and select <a href="http://squeryl.org/api/org/squeryl/dsl/fsm/SelectState.html" target="_blank">here</a>.</p>
<p>The statement should read like this: from Library.movie apply each row to the select function. The second set of parameters for from (the so called Queryable) can be expanded with where and order by clauses. For more information read the <a href="http://squeryl.org/selects.html" target="_blank">page about selects</a> on the Squeryl website.</p>
<p>The for loop of course prints all the movie names.</p>
<h3>&#8216;Advanced&#8217; queries</h3>
<p>The previous paragraph was just a simple query you&#8217;ll probably never execute in real life. So let&#8217;s try something a little bit more difficult:</p>
<pre class="brush: scala; title: ; notranslate">
inTransaction {
 val movies = from(Library.movie)(s=&gt;
 where(s.year === 1994)
 select(s) )
 println(movies)
 for (movie &lt;- movies){
 println (movie.name)
 }
}
</pre>
<p>The operator === is a method that is added to Int (this construction is called &#8216;implicit&#8217;) to create the actual where-statement in SQL. I also added a println(movies), this prints the actual SQL-statement, very useful!</p>
<h2>Conclusion</h2>
<p>I really like Squeryl, it was easy to set up and the basic documentation is sufficient. Of course a next step is inserting and adding more expressions (and for me, handling Postgis geometry objects).<br />
I hope this article gives you a head start.</p>
<h2>Sources</h2>
<p>-<a href="http://stackoverflow.com/questions/1362748/wanted-good-examples-of-scala-database-persistence" target="_blank">Stackoverflow &#8211; Examples of Scala database persistence</a><br />
-<a href="http://www.scala-lang.org/downloads" target="_blank">Scala installation</a><br />
-<a href="http://git-scm.com/" target="_blank">Git</a><br />
-<a href="https://github.com/harrah/xsbt/wiki/Setup" target="_blank">Sbt setup</a><br />
-<a href="http://twitter.com/#!/scweery" target="_blank">Scweery</a><br />
-<a href="http://squeryl.org" target="_blank">Squeryl</a><br />
-<a href="https://github.com/max-l/Squeryl/" target="_blank">Squeryl on github </a><br />
-<a href="http://groups.google.com/group/squeryl" target="_blank">Squeryl google group</a></p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F06%2F25%2Fscala-orm-with-squeryl%2F&amp;title=Scala%20ORM%20with%20Squeryl%20%26%238211%3B%20A%20simple%20getting%20started%20guide" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/06/25/scala-orm-with-squeryl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala Options the slick way</title>
		<link>http://blog.xebia.com/2011/06/02/scala-options-the-slick-way/</link>
		<comments>http://blog.xebia.com/2011/06/02/scala-options-the-slick-way/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 22:39:10 +0000</pubDate>
		<dc:creator>Urs Peter</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Uncategorized]]></category>

	<!-- AutoMeta Start -->
	<category>some_</category>
	<category>myopt</category>
	<category>ornone</category>
	<category>1234</category>
	<category>mkstring</category>
	<category>implicits</category>
	<category>converted</category>
	<category>dowithsomeval</category>
	<category>some_</category>
	<category>myopt</category>
	<category>ornone</category>
	<category>1234</category>
	<category>mkstring</category>
	<category>implicits</category>
	<category>converted</category>
	<category>dowithsomeval</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6933</guid>
		<description><![CDATA[The Scala Option type is key for dealing with variables that can have values or not. Most libraries and applications make use of this handy type. However, it&#8217;s usage in certain cases can lead to rather verbose code. This blog explains how to deal with this particular case in an elegant way using implicits. Read [...]]]></description>
			<content:encoded><![CDATA[<p>The Scala Option type is key for dealing with variables that can have values or not. Most libraries and applications make use of this handy type. However, it&#8217;s usage in certain cases can lead to rather verbose code. This blog explains how to deal with this particular case in an elegant way using implicits. Read on to see how easy it is to tailor any kind of existing Scala type to perfectly fit your needs based on an example with Options.<br />
<span id="more-6933"></span> </p>
<p>I love the Option type in Scala. Options provide a very concise way to express whether a variable can have a value or not. Whereas a programmer can express his/her intent in Scala in an extremely concise and compact way I must admit that this is not always true when dealing with Options.<br />
Depending whether I&#8217;m dealing with a Some() a want to convert the value of type X to a value of another type Y. Otherwise, in case it&#8217;s a None, I want to provide a default value of the target type Y. When writing Scala code I find myself using this construct quite often. To illustrate this let’s consider the following snippet:<br />
<code><br />
val myOpt:Option[Int] = Some(1234)<br />
val converted = myOpt match {<br />
case Some(v) => v.toString.reverse.mkString("-")<br />
case None => "unknown"<br />
}<br />
assert("4-3-2-1" == converted)<br />
</code></p>
<p>Basically, what we want to achieve here is a conversion from Int to a String depending whether the Option is of type Some(Int). Otherwise we want to provide a default value of “unkown”.</p>
<p>This is the only case I can think of where I can associate Scala with boilerplate code. Four lines of code to perform a simple conversion or provide a default value depending whether we are dealing with a Some or a None is quite a lot. The good news is, that there is an alternative. By using other methods of the Option API I could convert this into a one-liner as follows:</p>
<p><code><br />
val myOpt:Option[Int] = Some(1234)<br />
val converted = if(myOpt.isDefined) myOpt.get.toString.reverse.mkString("-") else "unknown"<br />
assert("4-3-2-1" == converted)<br />
</code></p>
<p>Apparently, it’s not that hard to put the desired conversion in one line of code, however, using conditional logic to achieve the desired result tempers my enthusiasm considerably. What I actually want is the following:</p>
<p><code><br />
val myOpt:Option[Int] = Some(1234)<br />
val converted = myOpt <strong>some_?</strong> (_.toString.reverse.mkString("-")) <strong>orNone</strong> "unknown"<br />
assert("4-3-2-1" == converted)<br />
</code></p>
<p>Personally, I would find such an API for Option very intuitive to use, concise, compact and fully OO. So, since it’s not there (yet) we have to come up with a solution ourselves. Since we want to add new functionality to an existing type without being able to modify the source code, the way to go are implicits. A possible solution looks as follows:<br />
<code><br />
implicit def fromOptionToConvertedVal[T](o:Option[T]) = new {<br />
         def some_?[R] (doWithSomeVal:(T) => R) = new {<br />
                  def orNone(handleNone: => R) = o match {<br />
                           case Some(value) => doWithSomeVal(value)<br />
                           case None => handleNone<br />
                  }<br />
         }<br />
}<br />
</code></p>
<p>What is happening here? We first define an implicit function, which takes an Option as parameter. The conversion returns an anonymous object, which contains one function with the name some_?. Any name would do of course. The some_? function is a higher order function that takes a function parameter of type T, which is the same as the one of the Option. The function parameter of some_? then returns a new type of R, since we want to convert the initial value of type T to R. </p>
<p>Instead of doing something within the function body, we return another anonymous object with the counterpart of some_? called orNone. The orNone function takes a call-by-name argument. The body of the orNone does the actual work. Based on whether the Option is a Some the function parameter of some_? is executed otherwise the call-by-name argument of the orNone, which leads to the desired result.</p>
<p>Bottom line: if you are missing something in any library you use in Scala, implicits provide you the perfect means to add everything you like so that it works for you. That is the real ‘option’ Scala offers you <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/06/02/scala-options-the-slick-way/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F06%2F02%2Fscala-options-the-slick-way%2F&amp;title=Scala%20Options%20the%20slick%20way" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/06/02/scala-options-the-slick-way/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Getting the Java out of your Scala</title>
		<link>http://blog.xebia.com/2011/04/03/getting-the-java-out-of-your-scala/</link>
		<comments>http://blog.xebia.com/2011/04/03/getting-the-java-out-of-your-scala/#comments</comments>
		<pubDate>Sun, 03 Apr 2011 15:24:39 +0000</pubDate>
		<dc:creator>Jan Vermeir</dc:creator>
				<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category>configdata</category>
	<category>jmsobjects</category>
	<category>elem</category>
	<category>parsing</category>
	<category>jmsobject</category>
	<category>jmsconfigfilename</category>
	<category>queue</category>
	<category>scala</category>
	<category>configdata</category>
	<category>jmsobjects</category>
	<category>elem</category>
	<category>parsing</category>
	<category>jmsobject</category>
	<category>jmsconfigfilename</category>
	<category>queue</category>
	<category>scala</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6620</guid>
		<description><![CDATA[To get some grip on the configuration of the Weblogic domains and servers at my current client, I created a tool that reads domain config files and translates them in a graph. I decided to solve this problem in Scala, mainly because I read about its powerful native XML parsing capabilities. Parsing XML turned out [...]]]></description>
			<content:encoded><![CDATA[<p>To get some grip on the configuration of the Weblogic domains and servers at my current client, I created a tool that reads domain config files and translates them in a graph. I decided to solve this problem in Scala, mainly because I read about its powerful native XML parsing capabilities. Parsing XML turned out to be a total no-brainer, but I managed to learn something about how to solve problems the Scala way, so this is a story about Scala rather than parsing XML in Scala.<br />
<span id="more-6620"></span><br />
To solve my problem I had to parse the configuration file for a Weblogic domain, or more specifically (in my case) the file where Weblogic stores information about JMS resources. Parsing one of those files is done like this:</p>
<pre class="brush: scala; title: ; notranslate">
    val configData: Elem = XML.loadFile(jmsConfigFileName)
</pre>
<p>configData now holds a parsed version of the file whose name is stored in jmsConfigFileName. This file contains stuff like queue and topic definitions like the fragment below:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;queue name=&quot;queueTo&quot;&gt;
    &lt;sub-deployment-name&gt;domain&lt;/sub-deployment-name&gt;
    &lt;jndi-name&gt;domain/jms/qto&lt;/jndi-name&gt;
  &lt;/queue&gt;
  &lt;topic name=&quot;domainJMSTopic&quot;&gt;
    &lt;sub-deployment-name&gt;domain&lt;/sub-deployment-name&gt;
    &lt;jndi-name&gt;domain/jms/topic&lt;/jndi-name&gt;
  &lt;/topic&gt;
</pre>
<p>My first attempt at retrieving all topic definitions from this config file was this:</p>
<pre class="brush: scala; title: ; notranslate">
  def findTopics(configData: Elem): Set[JmsObject] = {
    val jmsObjects = for (topic &lt;- (configData \\ &quot;topic&quot;))
      yield (new JmsTopic((topic \ &quot;@name&quot;).text, (topic \ &quot;jndi-name&quot;).text))
    jmsObjects.toSet
  }
</pre>
<p>I felt really happy about having written this powerful and concise loop. Scala&#8217;s for construct is powerful, as well as its XML parsing. To retrieve the queues I added the method below:</p>
<pre class="brush: scala; title: ; notranslate">
  def findQueues(configData: Elem): Set[JmsObject] = {
    val jmsObjects = for (queue &lt;- (configData \\ &quot;queue&quot;))
      yield (new JmsQueue((queue \ &quot;@name&quot;).text, (queue \ &quot;jndi-name&quot;).text))
    jmsObjects.toSet
  }
</pre>
<p>The duplication was obvious, so I felt a little less happy with my solution but I couldn&#8217;t see an easy way out. Enter my colleague and Scala trainer Urs Peter. He showed me two ways to improve the code.<br />
Our first attempt looks like this:</p>
<pre class="brush: scala; title: ; notranslate">
def buildListOfJmsObjectsFromConfigData[T]
           (configData:Elem, clazz:Class[T], startNode:String): Set[T] = {
    val jmsObjects = for (node &lt;- (configData \\ startNode))
      yield ( clazz.getConstructors.apply(0).newInstance(
                             (node \ &quot;@name&quot;).text
                           , (node \ &quot;jndi-name&quot;).text).asInstanceOf[T])
    jmsObjects.toSet
  }
</pre>
<p>Which you can then call like this:</p>
<pre class="brush: scala; title: ; notranslate">
buildListOfJmsObjectsFromConfigData (configData, classOf[JmsConnectionFactory]
           , &quot;connection-factory&quot;)
</pre>
<p>This looked quite Java-ish to me, as well as complex and obfuscated. </p>
<p>Our second attempt removes the loop and uses currying. It looks like  this:</p>
<pre class="brush: scala; title: ; notranslate">
def buildListOfJmsObjectsFromConfigData[T]
            (configData:Elem, startNode:String) (f:(NodeSeq) =&gt; T): Set[T] = {
     (configData \\ startNode).map(f).toSet
}
</pre>
<p>This second variant of buildListOfJmsObjectsFromConfigData[T] can be called like this:</p>
<pre class="brush: scala; title: ; notranslate">
      buildListOfJmsObjectsFromConfigData (configData, &quot;topic&quot;) {
        node =&gt; new JmsTopic((node \ &quot;@name&quot;).text, (node \ &quot;jndi-name&quot;).text)
      }
</pre>
<p>This works because the (configData \\ startNode) yields a set of objects on which we call map. Map takes a function as a parameter. The function shown above extracts a JmsTopic object, so we end up with a collection of JmsTopic instances. </p>
<p>I&#8217;m happy with our final version. It is concise and clear as well as extensible; way better than my first Java-ish version. </p>
<p><a href='http://blog.xebia.com/2011/04/03/getting-the-java-out-of-your-scala/java2scalablog/' rel='attachment wp-att-6624'>The code is attached here. </a><br />
I created three versions that are exercised in a unit test. JmsConfigReaderV1 is the first Java-ish version, JmsConfigReaderV2 is the compact but obfuscated solution and JmsConfigReaderV3 is my final attempt.<br />
I&#8217;m sure there are lots of opportunities to improve, so I welcome your opinions ans comments.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/04/03/getting-the-java-out-of-your-scala/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F04%2F03%2Fgetting-the-java-out-of-your-scala%2F&amp;title=Getting%20the%20Java%20out%20of%20your%20Scala" id="wpa2a_12"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/04/03/getting-the-java-out-of-your-scala/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Visiting the breeding grounds of Scala: EPFL</title>
		<link>http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/</link>
		<comments>http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 15:23:04 +0000</pubDate>
		<dc:creator>Urs Peter</dc:creator>
				<category><![CDATA[Scala]]></category>

	<!-- AutoMeta Start -->
	<category>breeding</category>
	<category>grounds</category>
	<category>lausanne</category>
	<category>epfl</category>
	<category>breeding</category>
	<category>grounds</category>
	<category>lausanne</category>
	<category>epfl</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6436</guid>
		<description><![CDATA[This week I visited the stronghold of Scala, EPFL, in order to certify as &#8216;official&#8217; Scala Trainer. It was an impressive visit, whose highlights I have transformed into this blog. This week I spent two days at EPF in Lausanne (EPFL), where I taught a module of Martin Odersky’s Scala course in order to certify [...]]]></description>
			<content:encoded><![CDATA[<p>This week I visited the stronghold of Scala, EPFL, in order to certify as &#8216;official&#8217; Scala Trainer. It was an impressive visit, whose highlights I have transformed into this blog.<br />
<span id="more-6436"></span></p>
<p>This week I spent two days at EPF in Lausanne (EPFL), where I taught a module of Martin Odersky’s Scala course in order to certify for ‘official’ Scala trainer. My teaching was followed and evaluated by the master himself, which was a unique experience. It definitely sounds more scary than it actually was. Nevertheless, it certainly was a once in a lifetime opportunity, great fun to do and fortunately with a positive outcome. </p>
<p>Being within the walls where Scala first has seen the light had more impact on me than I initially imagined. Realizing that all the highly modular and extendable building blocks of Scala were invented within these walls I started to grasp that this was just the beginning. Martin directs a great deal of research on new features for Scala, where he has the powerful position to cherry-pick the best of breed and integrate it into new versions of Scala. </p>
<p>While talking I learned that just some blocks away there was the research group who was porting Scala to the .Net platform. Martin’s assistant, Iulian Dragos, who taught another module of the Scala course wrote his thesis a.o. about the @specialized annotation, which is now part of Scala 2.8. Whereas parallel collections planned for 2.9 reached already an advanced stage I heard him talking about language virtualization (using the Scala compiler to compile to other languages), a ‘certified’ enterprise Scala stack, comparable to what RedHat does with JBoss, to ease the adoption for the enterprise, the beta eclipse Scala IDE, which is about to be released and so on, and so on. </p>
<p><a href="http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/withmoepfl/" rel="attachment wp-att-6440"><img src="http://blog.xebia.com/wp-content/uploads/2011/03/WithMOEPFL.jpg" alt="" title="WithMOEPFL" width="403" height="240" class="aligncenter size-full wp-image-6440" /></a><br />
Posing with Martin Odersky and the Swiss mountains surrounding EPFL</p>
<p>However, what I found most interesting to hear &#8211; being a consultant – is that many major Banks mostly in the States and Europe have started to embrace Scala, so far mostly for their business critical trading platforms. When besides innovative startups like Twitter and LinkedIn rather conservative enterprises dare to make such a move, I can hear a bell ring. </p>
<p>During the course it also became evident, that really a lot is going on. Martin had to delegate parts of the course to his assistant Iulian because of his myriads of current activities. Most of his free time during the course he spent mailing, reviewing papers etc. to manage the increasingly demanding Scala empire. He told me that because of lack of time he will delegate the Scala trainings to an associate, so that he can focus on the direction Scala is heading to. It became evident to me that Scala has grown far beyond the academic walls and is gaining serious ground in the industry. So all in all that is REALLY good news.</p>
<p>At the end of the first day there was another pleasing surprise waiting for me. Two local participants of the Scala course told me that at this very evening there is a meeting of the Scala user group of Lausanne and they asked me to join. Half an hour later I stood face to face with Ceki Gülcü, the inventor of log4j and other logging frameworks who is leading the Scala user group in Lausanne. Needless to say that it was a great evening, with lots of Scala live coding and geeky discussions. The next day we told Martin Odersky about our whereabouts, and because I mentioned that the amount of people joining the user group meeting wasn’t that impressive he answered: “Right, I think I should send them some Scala people from EPFL, to help them start up”. I wish our Scala user group in the Netherlands had such a highly elaborate Scala resource pool within reach… <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><a href="http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/scalausergroup/" rel="attachment wp-att-6439"><img src="http://blog.xebia.com/wp-content/uploads/2011/03/ScalaUserGroup.jpg" alt="" title="ScalaUserGroup" width="403" height="240" class="aligncenter size-full wp-image-6439" /></a><br />
Some people of the Scala user group Lausanne with Ceki Gülcü on the left.</p>
<p>There is another noteworthy anecdote. After lunch at the canteen of the EPFL Iulian pointed me to the other end of the aula, asking me whether I recognize ‘it’. What I saw was a fancy designed stairway, which triggered me at second glance. Have a look by yourself: </p>
<p><a href="http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/combined/" rel="attachment wp-att-6438"><img src="http://blog.xebia.com/wp-content/uploads/2011/03/combined.jpg" alt="" title="combined" width="240" height="403" class="aligncenter size-full wp-image-6438" /></a><br />
THE stairway to Scala</p>
<p>So far this blog has revealed everything else than fancy nuts and bolts of Scala. So to round up lets look at a neat little expression, which might find its way to Scala 2.9:</p>
<pre lang="scala">
def ??? = throw new IllegalArgumentException(“Not implemented yet”)
</pre>
<p>What we’ve defined is a method with the name ??? which throws an IllegalArgumentException. What’s so special about it? The interesting thing is that you can use the ??? method for all methods you have not implemented yet, no matter what type they return (a value type, Unit, a Function, Nothing etc.). Handy for prototyping: </p>
<pre lang="scala">
def myMethod(i:Int):String = ???
def myMethod(s:String, i:Int):Unit = ???
def myMethod:Int => Int= ???
</pre>
<p>So why does that compile? Because of Scala’s fundamental OO nature every method returns something. In case of void the returntype is Unit, in case a method only throws an exception the returntype is Nothing. Therefore, the returntype of the ??? method is of type Nothing. Without making use of Scala’s type inference I would have to write:</p>
<pre lang="scala">
def ???():Nothing = throw new IllegalArgumentException(“not implemented yet”)
</pre>
<p>When you look at the class hierarchy of Scala you see that Nothing is the sub type of every type. Since you always can return a sub type of the actually defined type you return in a method, the Nothing type is a valid return type for anything. As you probably assumed, the Nothing type is added by the compiler. There is no way and need to deal with the Nothing type explicitly. Personally, I find this a smart and powerful construct, stressing once more Scala’s flawless class hierarchy setup. </p>
<p>All in all, it was a great and special experience to visit the breeding grounds of Scala, whose gifted creator is leading this impressive language to new heights, for years of fun and productivity to come for all daring to step over the threshold.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F03%2F20%2Fvisiting-the-breeding-grounds-of-scala-epfl%2F&amp;title=Visiting%20the%20breeding%20grounds%20of%20Scala%3A%20EPFL" id="wpa2a_14"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/03/20/visiting-the-breeding-grounds-of-scala-epfl/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/category/scala/feed/ ) in 0.83467 seconds, on Feb 9th, 2012 at 3:52 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 4:52 pm UTC -->
