<?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>Jayway Team Blog &#187; scala</title>
	<atom:link href="http://blog.jayway.com/tag/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +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>Getting Started with Spring Data &#8211; MongoDB in Scala</title>
		<link>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/</link>
		<comments>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 15:11:14 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[spring data]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10621</guid>
		<description><![CDATA[I used MongoDB for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production In this post I want to show you a [...]]]></description>
			<content:encoded><![CDATA[<p>I used <a title="MongoDB" href="http://www.mongodb.org/">MongoDB</a> for a project in 2010 and I had great experience with it. Unfortunately I didn't get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this post I want to show you a step by step guide on how you can start your Scala project with <a title="Spring Data" href="http://www.springsource.org/spring-data/mongodb">Spring Data</a> for MongoDB.</p>
<p>You should have <a title="SBT" href="https://github.com/harrah/xsbt">SBT</a> 0.11 installed on your system since I am going to use it as the building tool through out this post.</p>
<h3>1. Creating Project</h3>
<p>Create the project like below:</p>
<pre>$ mkdir springDataMongo
$ cd springDataMongo/
$ sbt
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to default-71a5a0 (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set name := "SpringMongo"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set version := "1.0"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; set scalaVersion := "2.9.1"
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; session save
[info] Reapplying settings...
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)</pre>
<p>Open file build.sbt and add the dependencies:</p>
<p><script src="https://gist.github.com/1309234.js?file=build.sbt"></script></p>
<p>Save the file and run the following in SBT console:</p>
<pre>&gt; reload
[info] Loading global plugins from /home/amir/.sbt/plugins
[info] Set current project to SpringMongo (in build file:/data/3-Projects/scala-projects/springDataMongo/)
&gt; update
[info] Updating {file:/data/3-Projects/scala-projects/springDataMongo/}default-71a5a0...
[info] Done updating.</pre>
<p>And generate the IDE related files. I am using IntelliJ:</p>
<pre>&gt; gen-idea</pre>
<p>or if you use Eclipse:</p>
<pre>&gt; eclipse create-src</pre>
<p>Now you have configured your project and you can start coding!</p>
<h3>2. Configuring Spring</h3>
<p>There are two ways to configure Spring Data for MongoDB: Annotations and XML. I explain annotations here. You have to extend <span style="text-decoration: underline;">AbstractMongoConfiguration</span> class as follows to define your database settings:</p>
<p><script src="https://gist.github.com/1309234.js?file=MongoConfig.scala"></script></p>
<p>As you see there are two methods to implement. <span style="text-decoration: underline;">mongo</span> method should return an instance of Mongo class. If you are using a mongo instance in a network, you should then specify the address and possibly port (if not the default).</p>
<h3>3. Data Model</h3>
<p>Consider we have the following class for keeping accounts in a system. This class will be mapped to a mongo document by Spring:</p>
<p><script src="https://gist.github.com/1309234.js?file=Account.scala"></script></p>
<h3>4. Interacting with MongoDB</h3>
<p>Now let's write a simple program to interact with MongoDB:</p>
<p><script src="https://gist.github.com/1309234.js?file=App.scala"></script></p>
<p><span style="text-decoration: underline;">mongoTemplate</span> is an implementation of <span style="text-decoration: underline;">MongoOperation</span> interface. With <span style="text-decoration: underline;">MongoOperation</span> you can do all CRUD operations. E.g. inserting/saving a document:</p>
<p><script src="https://gist.github.com/1309234.js?file=SaveAccount.scala"></script></p>
<p>"accounts" is the name of collection. Or if you want to query:</p>
<p><script src="https://gist.github.com/1309234.js?file=Query.scala"></script></p>
<p>Note that <span style="text-decoration: underline;">JavaConversions</span> is required here since the result of <span style="text-decoration: underline;">find</span> is a <span style="text-decoration: underline;">java.util.List[Account]</span> and we need to convert it to Scala list.</p>
<p>Please refer to <a title="documentation" href="http://www.springsource.org/spring-data/mongodb#documentation">documentation</a> of Spring Data for MongoDB for more info about what you can do more <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/24/getting-started-with-spring-data-mongodb-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala LiftOff London 2011</title>
		<link>http://blog.jayway.com/2011/10/18/scala-liftoff-london-2011/</link>
		<comments>http://blog.jayway.com/2011/10/18/scala-liftoff-london-2011/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 19:17:41 +0000</pubDate>
		<dc:creator>Björn Antonsson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10581</guid>
		<description><![CDATA[Last week I attended Scala LiftOff London 2011 at the Skills Matters Exchange, and being very new to the community aspect of Scala i didn't know what to expect. One thing is for sure, I could never have imagined the kind of  sharing and positive atmosphere that I got from the people there. There where lots of interesting talks [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I attended <a href="http://skillsmatter.com/event/scala/scala-lift-off-london-2011/">Scala LiftOff London 2011</a> at the Skills Matters Exchange, and being very new to the community aspect of Scala i didn't know what to expect. One thing is for sure, I could never have imagined the kind of  sharing and positive atmosphere that I got from the people there.</p>
<p>There where lots of interesting talks on a wide variety of subjects, all the way from <a href="http://skillsmatter.com/podcast/scala/parallel-algorithms-data-structures">low level bit shifting in concurrent data structures</a> all the way to how you <a href="http://skillsmatter.com/podcast/scala/real-time-betting-lift">build a real time sports betting system with Scala and Lift</a> or <a href="http://skillsmatter.com/podcast/scala/lift-jee">integrate your Scala code with existing JEE applications</a>. There is no doubt that there are lots of things happening around Scala right now, and the pace is fast.</p>
<p>One thing that really hit home though was the excellent <a href="http://skillsmatter.com/podcast/scala/welcome">keynote by David Pollak</a>  that asked the question if Scala had really crossed the chasm, and reminded us that history is full of brilliant technology that has failed, since no single product can survive on technical merit alone.</p>
<p>But how can we ensure that Scala is successful? The obvious answers are of course tooling, support and continued innovation, but an equally important aspect is probably accessibility. People, both programmers, managers and other decision makers, need to feel at home with Scala. So we need to show them just how easy, familiar and powerful Scala is. This is where Phil Bagwells presentation about Kojo comes into the picture.</p>
<p><a href="http://kogics.net/sf:kojo">Kojo</a> is a Scala based learning tool that was designed for teaching kids, but as Phil pointed out "We are all just 11 year olds mentally, who like shiny toys". That fact makes Kojo an excellent presentation tool. By not only showing people static slides with code and promises (yes I'm guilty of this as well), but letting them interact with the code in the presentation Kojo makes Scala directly and easily accessible.</p>
<p><a href="http://kogics.net/sf:kojo">Kojo</a> is a simple download if you have Java installed, and Phil kindly let me post his <a href="https://gist.github.com/1286624">story</a> (that's what they're called in Kojo) on github.</p>
<p>So download <a href="http://kogics.net/sf:kojo">Kojo</a>, download the <a href="https://gist.github.com/1286624">story</a>, load it up, play with it, share it and introduce some people the wonders of Scala.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/scala-liftoff-london-2011/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Experimenting with Scala Parallel Collections (contd.)</title>
		<link>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/</link>
		<comments>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 12:35:01 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10535</guid>
		<description><![CDATA[In the previous post we went through Scala parallel collections and you saw how you can convert a sequential collection into a parallel one by using method par on that collection. In this post I want to show you how you can write your own parallel collection in Scala. The example I use for this [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous <a title="post" href="http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/">post</a> we went through Scala parallel collections and you saw how you can convert a sequential collection into a parallel one by using method <strong>par</strong> on that collection.</p>
<p>In this post I want to show you how you can write your own parallel collection in Scala. The example I use for this post is taken from Alex Prokopec's presentation at Scala eXchange 2011.</p>
<p>Consider we want to have a parallel String in our application. If you convert a String into a parallel collection you get a <span style="text-decoration: underline;">ParArray</span>:</p>
<pre>scala&gt; "I Love Scala".par
res2: scala.collection.parallel.ParSeq[Char] = ParArray(I,  , L, o, v, e,  , S, c, a, l, a)</pre>
<p>This is good enough to take advantage of your multi-core CPU architecture, but for some reason you want to write you own Parallel String collection!</p>
<p>Scala Parallel collection is implemented by a mechanism that is called <em>split-combine</em>. As the name implies a sequential collection can be <em>splitted</em> into sub-collections and each one can be stolen by a thread from a thread pool. Later the results of each sub-collection can be <em>combined</em> to make the final collection. You can find details about this implementation in [1].</p>
<p>In order to start with our Parallel String we need to extend <span style="text-decoration: underline;">scala.collection.parallel.immutable.ParSeq</span> trait. There are 4 abstract methods that we need to implement:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringV1.scala"></script></p>
<p><span style="text-decoration: underline;">seq</span>, <span style="text-decoration: underline;">length</span> and <span style="text-decoration: underline;">apply</span> have obvious implementations. Method <span style="text-decoration: underline;">splitter</span> returns a new instance of class <span style="text-decoration: underline;">ParallelStringSplitter</span> which we are going to define next. Note that this instance is mixed-in into <span style="text-decoration: underline;">SignalContextPassingIterator</span> which is responsible for passing the signal context along iterators. We define <span style="text-decoration: underline;">ParallelStringSplitter</span> class inside ParallelString class:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringSplitter.scala"></script></p>
<p>Note that we need to extend <span style="text-decoration: underline;">Splitter</span> trait. There are 6 abstract methods to implement. Method <span style="text-decoration: underline;">dup</span> returns a new instance of <span style="text-decoration: underline;">ParallelStringSplitter</span> with current values. Method <span style="text-decoration: underline;">split</span> splits the iterator into a sequence of disjunct views and method <span style="text-decoration: underline;">psplit</span> splits the splitter into a sequence of disjunct views.</p>
<p>Now we have the splitter. Let's test this parallel String in REPL:</p>
<pre>scala&gt; val pstr = new ParallelString("This is a long string" * 250000)
pstr: ParallelString = ParallelString(T, h, i, s,  , i, s,  , a,  , l, o, n, g,  ...</pre>
<p>If you don't provide a combiner, then the default one is used. Sometimes you want to have control over the combination and you want to take the responsibility for it. Let's write our own combiner to show how you can do that. We need to mix in another trait into the definition of <span style="text-decoration: underline;">ParallelString</span>: <span style="text-decoration: underline;">ParSeqLike</span></p>
<p><script src="https://gist.github.com/1295051.js?file=WithCombiner.scala"></script></p>
<p>In order to specify our own combiner we need to override method <span style="text-decoration: underline;">newCombiner</span>:</p>
<p><script src="https://gist.github.com/1295051.js?file=Combiner.scala"></script></p>
<p>Now we need to define <span style="text-decoration: underline;">ParallelStringCombiner</span> class by extending the <span style="text-decoration: underline;">Combiner</span> trait:</p>
<p><script src="https://gist.github.com/1295051.js?file=ParallelStringCombiner.scala"></script></p>
<p>There are 5 abstract methods that need to be implemented. As the names imply method <span style="text-decoration: underline;">combine</span> combines the content of another builder to the current builder and produces a new builder. Method <span style="text-decoration: underline;">result</span> produces a collection from added elements and <span style="text-decoration: underline;">+=</span> adds a single element to this builder.</p>
<p>To summarize, to build a parallel collection class <span style="text-decoration: underline;">A</span>, one should:</p>
<ul>
<li>extend <span style="text-decoration: underline;">ParSeq</span> trait</li>
<li>implement all abstract methods from <span style="text-decoration: underline;">ParSeq</span> trait</li>
<li>define a splitter class that mixes in with <span style="text-decoration: underline;">Splitter</span> and <span style="text-decoration: underline;">ParIterator</span> traits and put it in class <span style="text-decoration: underline;">A</span></li>
<li>extend <span style="text-decoration: underline;">ParSeqLike</span> trait</li>
<li>define a combiner class that extend <span style="text-decoration: underline;">Combiner</span> trait and implement all abstract methods</li>
<li>override <span style="text-decoration: underline;">newCombiner</span> method in class <span style="text-decoration: underline;">A</span> and return a new instance of defined combiner</li>
</ul>
<p>For the complete code of this example please refer to <a title="Alex Prokopec's Github" href="https://github.com/axel22/sd/blob/master/src/main/scala/scaladays/ParString.scala">Alex Prokopec's Github</a>.</p>
<h3>References</h3>
<p>[1]: Aleksandar Prokopec, Tiark Rompf, Phil Bagwell, Martin Odersky, "A Generic Parallel Collection Framework", Euro-Par 2011</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/18/experimenting-with-scala-parallel-collections-contd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Injectors and Extractors in Scala</title>
		<link>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/</link>
		<comments>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 14:05:46 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[case]]></category>
		<category><![CDATA[extractor]]></category>
		<category><![CDATA[injector]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10253</guid>
		<description><![CDATA[If you have used case classes in Scala, you can not neglect the power they bring to your applications. They provide a recursive decomposition mechanism via pattern matching. In this post I go through injectors and mostly extractors. You will see that how extractors can be employed for pattern matching. Consider that we need to [...]]]></description>
			<content:encoded><![CDATA[<p>If you have used <em>case</em> classes in Scala, you can not neglect the power they bring to your applications. They provide a recursive decomposition mechanism via pattern matching.</p>
<p>In this post I go through injectors and mostly extractors. You will see that how extractors can be employed for pattern matching.</p>
<p>Consider that we need to hold first names in an application. We can define a case class for <span style="text-decoration: underline;">Firstname</span>:</p>
<p><script src="https://gist.github.com/1280657.js?file=Firstname.scala"></script></p>
<p>we build a value from this case class in REPL:</p>
<pre>scala&gt; val fname = Firstname("Amir")
fname: Firstname = Firstname(Amir)</pre>
<p>and now a pattern matching on this case class:</p>
<pre>scala&gt; fname match {
     |     case Firstname(f) =&gt; println(f)
     |     case _            =&gt; println("Nothing found")
     | }
Amir</pre>
<p>Here <span style="text-decoration: underline;">fname</span> is matched against its case class by constructor patterns mechanism and its field is extracted and printed. Very powerful and handy.</p>
<p>What if we need to do a pattern matching for a string? The problem is that strings are not case classes.</p>
<p>Scala provides us with a very interesting mechanism called Extractors. An extractor is an object that has a method called <strong>unapply</strong> as one of its members. Let's clarify this with an example: assume we want to have an extractor object for IP addresses. We define the extractor as the following:</p>
<p><script src="https://gist.github.com/1280657.js?file=IPAddress.scala"></script></p>
<p>Method <span style="text-decoration: underline;">unapply</span> receives a string representing a possible IP address and returns an option of 4 strings. If the string is not a valid IP address, the method returns None. Method <span style="text-decoration: underline;">isValid</span> is added for validating IP addresses. Let's try this in REPL:</p>
<pre>scala&gt; val ip = "127.0.0.1"
ip: java.lang.String = 127.0.0.1

scala&gt; val nonIP = "128.-112.ABC."
nonIP: java.lang.String = 128.-112.ABC.

scala&gt; IPAddress.unapply(ip)
res0: Option[(String, String, String, String)] = Some((127,0,0,1))

scala&gt; IPAddress.unapply(nonIP)
res1: Option[(String, String, String, String)] = None</pre>
<p>And if we use it in a pattern matching statement:</p>
<pre>scala&gt; ip match {
     |    case IPAddress(_, _, _, a) =&gt; println(a)
     |    case _                     =&gt; println("Invalid ip address")
     | }
1

scala&gt; nonIP match {
     |    case IPAddress(_, _, _, a) =&gt; println(a)
     |    case _                     =&gt; println("Invalid ip address")
     | }
Invalid ip address</pre>
<p>So <span style="text-decoration: underline;">ip</span> was a valid string representation of an IP Address and it is matched against <span style="text-decoration: underline;">IPAddress</span> while <span style="text-decoration: underline;">nonIP</span> was not a valid one. In the example above we were only interested in the last byte of IP Address and we skipped the rest by _ wildcard. Of course you can extract all the four parts if you need them.</p>
<p>In <span style="text-decoration: underline;">IPAddress</span> object we used 4 variables that is wrapped in a <em>Some</em> in the success case and returned. This can be generalized to <em>N</em> variables.</p>
<p>It is also possible that an extractor pattern does not bind to any variables. In this case the corresponding <span style="text-decoration: underline;">unapply</span> method returns a boolean (<em>true</em> for success and <em>false</em> for failure). As an example we changed the unapply method to the following:</p>
<p><script src="https://gist.github.com/1280657.js?file=NoBinding.scala"></script></p>
<p>and we try it in REPL:</p>
<pre>scala&gt; "127.0.0.1" match {
     |    case IPAddress() =&gt; println("Valid")
     |    case _           =&gt; println("Invalid")
     | }
Valid</pre>
<p>Remember that although there is no binding in this case but you have to put the parentheses in front of <span style="text-decoration: underline;">IPAddress</span>.</p>
<p>So far we have seen fixed number of element values. But what if we have variable number of element values? For example if you have a string that can contain arbitrary number of IP addresses? In order to handle this case, Scala allows you to define a different extractor method called <strong>unapplySeq</strong>. To see how it can be used, assume we want to have pattern matching on a string containing arbitrary number of IP Addresses:</p>
<p><script src="https://gist.github.com/1280657.js?file=IPAddresses.scala"></script></p>
<p>This time the method returns an option of a sequence of string. Now let's see what we can do with it:</p>
<pre>scala&gt; val ips = "192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4"
ips: java.lang.String = 192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4

scala&gt; ips match {
     |    case IPAddresses(IPAddress(a, _, _, _), IPAddress(b, _, _, _), _*) =&gt; println(a + " " + b)
     |    case _                                                             =&gt; println("Invalid IP addresses")
     | }
192 192</pre>
<p>In this example we used both <span style="text-decoration: underline;">IPAddress</span> and <span style="text-decoration: underline;">IPAddresses</span> objects in the pattern matching. There are 4 IP addresses in <span style="text-decoration: underline;">ips</span> and we are looking for the first byte of the first two IPs in the string. How powerful and clean!</p>
<p>The <span style="text-decoration: underline;">unapply</span> method is called <em>extractor</em> because it takes an element of the same set and extracts some of its parts. In our example <span style="text-decoration: underline;">IPAddress</span> takes a string and validates and extracts all 4 bytes of the address. You can also define a method <span style="text-decoration: underline;">apply</span> on an object that does vice versa which takes some arguments and yields an element of a given set. This method is called an <em>injection</em>. We can define injection for our <span style="text-decoration: underline;">IPAddress</span> object like this:</p>
<p><script src="https://gist.github.com/1280657.js?file=Injector.scala"></script></p>
<p>Injections and extractions are often located in the same object because then you can use the object name for both constructions and pattern matching. However, it is also possible to have an extraction object without injection. The object itself is called <em>extractor</em> regardless of whether or not it has an apply method [1].</p>
<p>Remember if you include the injection method, it should be a dual to the extraction method, for example:</p>
<pre>IPAddress.unapply( IPAddress.apply(a, b, c, d) )</pre>
<p>should return:</p>
<pre>Some(a,b,c,d)</pre>
<h3>Extractors vs. Case classes</h3>
<p>There is a section in [1] that compares extractors and case classes which I summarize here:</p>
<ul>
<li>There is one shortcoming with case classes: they expose the <em>concrete representation of data</em>. This means that if a case succeeds in a matching, you know that the selector expression is an instance of that case class.</li>
<li>Extractors do not expose the concrete representation of data.</li>
<li>Case classes have less code and they are easier to set up. Scala compiler can optimize patterns over case classes much better than extractors.</li>
<li>If a case class inherits from a sealed base class, Scala compiler checks for pattern matches for exhaustiveness and will complain in case there exists something while Scala compiler can not do the same thing for extractors.</li>
<li>If you write code for a <em>closed application</em>, case classes are preferable because of their advantages in conciseness, speed and static checking.</li>
<li>If you need to expose a type to unknown clients, extractors might be preferable.</li>
</ul>
<p>&nbsp;</p>
<p><span class="Apple-style-span" style="font-size: 15px; font-weight: bold;">References:</span></p>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/11/injectors-and-extractors-in-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part three</title>
		<link>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/</link>
		<comments>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 11:05:50 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[lower-bound]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[upper-bound]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9977</guid>
		<description><![CDATA[So far we have seen how to define covariant and contravariant subtypes in Scala. In this post we will study lower bounds and upper bounds and see how they can be of great help when designing your application. Lower bounds Consider the class I defined in the first post: Company is covariant in type T [...]]]></description>
			<content:encoded><![CDATA[<p>So far we have seen how to define <a title="covariant" href="http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/">covariant</a> and <a title="contravariant" href="http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/">contravariant</a> subtypes in Scala. In this post we will study lower bounds and upper bounds and see how they can be of great help when designing your application.</p>
<h3>Lower bounds</h3>
<p>Consider the class I defined in the first post:</p>
<p><script src="https://gist.github.com/1280571.js?file=Company.scala"></script></p>
<p>Company is covariant in type <em>T</em> as you know by now. It's been a while and we realize it's the time to define a partnership relation for companies to connect them together and expand their co-operations. So we add the following method to <span style="text-decoration: underline;">Company</span> class:</p>
<p><script src="https://gist.github.com/1280571.js?file=PartnerDef.scala"></script></p>
<p>When we try to compile this code we get:</p>
<pre>Error: covariant type T occurs in contravariant position in type T of value y</pre>
<p>What happened here? To see what has happened it's better to take a look at Function1 definition in Scala:</p>
<p><script src="https://gist.github.com/1280571.js?file=Function1.scala"></script></p>
<p>This definition tells us that the input of a function is contravariant (negative) and what it returns is covariant (positive). So remember that no matter how many arguments a function has, all of them are in negative positions:</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/function2.png" rel="lightbox"><img class="aligncenter size-medium wp-image-9991" title="function" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/function2-300x111.png" alt="" width="300" height="111" /></a></p>
<p>Now it should be more clear why we got the compile error. We were passing an argument of type <em>T</em> which is covariant (positive) and we know that arguments of a function has negative (contravariant) positions. This is a contradiction.</p>
<p>But how can we solve this? We can use lower type bounds to parameterize a method.</p>
<p><em>Lower type bounds</em>: help you to declare a type to be a supertype of another type. <em>T</em> &gt;: <em>A</em> indicates that type <em>T</em> or abstract type <em>T</em> refers to a supertype of type <em>A</em>.</p>
<p>Let's correct the defined method by using lower bounds:</p>
<p><script src="https://gist.github.com/1280571.js?file=NewPartnerDef.scala"></script></p>
<p>By this new definition, <span style="text-decoration: underline;">partnerWith</span> method accepts arguments that can be supertype of type <em>T</em>.</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@149bc5a

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@116ac04

scala&gt; bigCompany.partnerWith(littleCompany)</pre>
<p>So <span style="text-decoration: underline;">partnerWith</span> method is now generalized and polymorphic.</p>
<h3>Upper bounds</h3>
<p>Assume that we want to restrict the partnership relation somehow in our example. We wanna say that a company can have partnership with another company that is a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>. In order to apply this restriction in Scala, one can use upper bounds. So let's change the <span style="text-decoration: underline;">partnerWith</span> method to reflect this:</p>
<p><script src="https://gist.github.com/1280571.js?file=UpperboundPartner.scala"></script></p>
<p>Now <span style="text-decoration: underline;">partnerWith</span> only accepts arguments that are a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>. Let's prove this by introducing a new company:</p>
<p><script src="https://gist.github.com/1280571.js?file=CrappyCompany.scala"></script></p>
<p>This class does not extend <span style="text-decoration: underline;">BigCompany</span> so <span style="text-decoration: underline;">Company[CrappyCompany]</span> is not a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span> according to covariant type declaration. Now we try to build partnerships in REPL:</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@1979eb4

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@6d1901

scala&gt; littleCompany.partnerWith(bigCompany)

scala&gt; val crappyCompany: Company[CrappyCompany] = new Company[CrappyCompany](new CrappyCompany)
crappyCompany: Company[CrappyCompany] = Company@1d0d313

scala&gt; littleCompany.partnerWith(crappyCompany)
&lt;console&gt;:11: error: inferred type arguments [Company[CrappyCompany]] do not conform to method 
partnerWith's type parameter bounds [U &lt;: Company[BigCompany]]
       littleCompany.partnerWith(crappyCompany)
                     ^</pre>
<p>So by upper type bound declaration we could restrict our partnership relation.</p>
<p>Remember that by definition a class is supertype and subtype of itself. Hence you can pass an instance of <span style="text-decoration: underline;">Company[BigCompany]</span> to <span style="text-decoration: underline;">partnerWith</span>:</p>
<pre>scala&gt; val bigCompany2 : Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany2: Company[BigCompany] = Company@b61e92

scala&gt; bigCompany.partnerWith(bigCompany2)</pre>
<p>Note that both lower and upper bound declarations have the colon as their second character so you don't mix the order ( &lt;: &gt;: )</p>
<h3>Conclusion</h3>
<p>In these three posts I showed how you can avail from Scala variance annotations and lower and upper bounds together to design your application in a type safe manner. Scala provides you with <em>type-driven design</em> where types of an interface guides its detailed design and implementation [1]. Examples provided in these posts were not the best examples but they could still show the purpose of their existence. I hope you have a better understanding of this cool feature in Scala.</p>
<p>&nbsp;</p>
<h3>References</h3>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part two</title>
		<link>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/</link>
		<comments>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 10:18:11 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[contravariant]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9907</guid>
		<description><![CDATA[In the previous post, I went through what covariant subtyping is. In this post we will study contravariant subtyping with a small example. Contravariant Subtyping Do you remember the definition of covariant? Contravariant is the other way around. I will clarify this by the following example (example is adopted from [1]). Consider we have a [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous <a title="post" href="http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/">post</a>, I went through what covariant subtyping is. In this post we will study contravariant subtyping with a small example.</p>
<h3>Contravariant Subtyping</h3>
<p>Do you remember the definition of covariant? Contravariant is the other way around. I will clarify this by the following example (example is adopted from [1]). Consider we have a trait:</p>
<p><script src="https://gist.github.com/1280571.js?file=NetworkChannel.scala"></script></p>
<p>This trait has a write method that is responsible for accepting an argument and writing it in the current network channel. Assume that we have two <span style="text-decoration: underline;">NetworkChannel</span> of type AnyRef and String:</p>
<p><script src="https://gist.github.com/1280571.js?file=ChannelImpl.scala"></script></p>
<p>We just don't care about the write implementation now. There is another class that is responsible for controlling output channels:</p>
<p><script src="https://gist.github.com/1280571.js?file=BufferControl.scala"></script></p>
<p>The control method accepts an argument of type <span style="text-decoration: underline;">NetworkChannel[String]</span>. Do you think we can pass <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> to this method? Yes we can! <span style="text-decoration: underline;">NetworkChannel</span> is declared to be contravariant in its type T.</p>
<p>Contrvariant subtyping means: <strong>If <em>S</em> is a subtype of <em>T</em> then NetworkChannel[<em>T</em>] is a subtype of NetworkChannel[<em>S</em>]</strong></p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contra1.png" rel="lightbox"><img class="size-medium wp-image-9921 aligncenter" title="contra1" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contra1-300x175.png" alt="" width="300" height="175" /></a></p>
<p>This seems to be a little bit strange in our example. We know that String is a subtype of AnyRef in Scala. How come <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> can be a subtype of <span style="text-decoration: underline;">NetworkChannel[String]</span> ?</p>
<p>Consider what you can do with each channel. <span style="text-decoration: underline;">NetworkChannel[String]</span> accepts arguments of type String and write them in network channel. <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> accepts arguments of type AnyRef and write them also in network channel. We can substitute <span style="text-decoration: underline;">NetworkChannel[String]</span> with <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> since whatever can be done by <span style="text-decoration: underline;">NetworkChannel[String]</span> can be done also by <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> (remember that <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> can also write strings) but not vice versa. We can not use <span style="text-decoration: underline;">NetworkChannel[String]</span> instead of <span style="text-decoration: underline;">NetworkChannel[AnyRef]</span> since it only accepts strings.</p>
<p>Remember that contravariant orders types from more <em>genetic</em> to more <em>specific.</em></p>
<p>How should I know if two types are covariants or contravariants? Read the following section.</p>
<h3>Liskov Substitution Principle (LSP)</h3>
<p>LSP is a principle in object-oriented programming. It states:</p>
<blockquote><p>It is safe to assume that S is a subtype of T if you can substitute a value of type S wherever a value of type T is required without violating the desirable properties of the program [2].</p></blockquote>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contravariantSubTyping1.png" rel="lightbox"><img class="aligncenter size-full wp-image-9929" title="contravariantSubTyping" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/contravariantSubTyping1.png" alt="" width="535" height="283" /></a></p>
<p>So let's say we have <em>S</em> as a subtype of <em>T</em>. If Class of type <em>S</em> is a subtype of Class of type <em>T</em> then there is a <strong>covariant</strong> subtyping between them. Otherwise if Class of type <em>T</em> is a subtype of Class of type <em>S</em> then there is <strong>contravariant</strong> subtyping between them. if there is no subtyping relation between Class of type <em>S</em> and <em>T</em>, then there is <strong>invariant</strong> subtyping relation.</p>
<p>I hope you have understood Scala Types variances. In the next <a title="post" href="http://blog.jayway.com/2011/10/05/scala-type-variances-part-three/">post</a> I will discuss Lower bounds and upper bounds.</p>
<h3>References</h3>
<p>[1]: Martin Odersky, Lex Spoon, Bill Venners, "Programming in Scala", 2nd Edition<br />
[2]: Barbara Liskov, Jeannette Wing, "A behavioral notion of subtyping", ACM Transactions on Programming Languages and Systems (TOPLAS), Volume 16, Issue 6 (November 1994), pp. 1811 – 1841</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Scala Type Variances &#8211; Part one</title>
		<link>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/</link>
		<comments>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 16:34:43 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[covariant]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[subtyping]]></category>
		<category><![CDATA[type]]></category>
		<category><![CDATA[variance]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9867</guid>
		<description><![CDATA[I remember when I started to learn Scala, I usually come up with brackets in the Scala API doc that have plus and minus characters inside. Honestly that scared me a little bit! But after I learned a bit about Scala type system, I know the purpose of theses type declarations and I appreciate their [...]]]></description>
			<content:encoded><![CDATA[<p>I remember when I started to learn Scala, I usually come up with brackets in the Scala API doc that have plus and minus characters inside. Honestly that scared me a little bit! But after I learned a bit about Scala type system, I know the purpose of theses type declarations and I appreciate their designer <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In this series of posts I will try my best to clear out type variance annotations in Scala; a powerful tool to handle type orderings from specific to generic and vice verca.</p>
<h3>Covariant Subtyping</h3>
<p>We start by covariant subtyping. If you don't know what it is, please be patient. First consider the following code in Scala:</p>
<p><script src="https://gist.github.com/1280571.js?file=CompanyAndInvestor.scala"></script></p>
<p>We have a <span style="text-decoration: underline;">Company</span> class that has type parameter <em>T</em>. This class accepts a value of type <em>T</em> for its constructor. We have two companies defined here: <span style="text-decoration: underline;">BigCompany</span> and <span style="text-decoration: underline;">SmallCompany</span>. As it is obvious from the code <span style="text-decoration: underline;">SmallCompany</span> is a subtype of <span style="text-decoration: underline;">BigCompany</span>. Finally we have a class Investor that accepts only companies of type <span style="text-decoration: underline;">BigCompany</span> so it invests only on big ones!<br />
Now let's do some constructions in REPL:</p>
<pre>scala&gt; val littleCompany: Company[SmallCompany] = new Company[SmallCompany](new SmallCompany)
littleCompany: Company[SmallCompany] = Company@1e70822

scala&gt; val bigCompany: Company[BigCompany] = new Company[BigCompany](new BigCompany)
bigCompany: Company[BigCompany] = Company@9bb740

scala&gt; val bigInvestor:Investor = new Investor(bigCompany)
bigInvestor: Investor = Investor@1004566</pre>
<p>So far so good. After a while it is decided that we need investors that can take care of small companies. We don't want to define a new brand of investor thus we use the existing one. So we try to construct:</p>
<pre>scala&gt; val smallInvestor:Investor = new Investor(littleCompany)</pre>
<p>But we get:</p>
<pre>&lt;console&gt;:8: error: type mismatch;
 found   : Company[SmallCompany]
 required: Company[BigCompany]
Note: SmallCompany &lt;: BigCompany, but class Company is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
       val smallInvestor:Investor = new Investor(littleCompany)
                                                 ^</pre>
<p>Bang! What happened? Compile error!</p>
<p>Let's see what happened exactly here. We know by definition that <span style="text-decoration: underline;">SmallCompany</span> is subtype of <span style="text-decoration: underline;">BigCompany</span>. But what is the relation between <span style="text-decoration: underline;">Company[</span><span style="text-decoration: underline;">SmallCompany]</span> and <span style="text-decoration: underline;">Company[BigCompany]</span> ? It is not defined by default and we need somehow to tell compiler about this. In order to solve this we change class <em>Company</em> to the following:</p>
<p><script src="https://gist.github.com/1280571.js?file=Company.scala"></script></p>
<p>The only thing that is changed is the type parameter that has a + sign in front. This means that subtyping is covariant (flexible) in paramter <em>T</em>.</p>
<p>Covariant subtyping means: <strong>if <em>S</em> is a subtype of <em>T</em> then Company[<em>S</em>] is subtype of Company[<em>T</em>]</strong>.</p>
<p style="text-align: center;"><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/convariantSubTyping1.png" rel="lightbox"><img class="size-medium wp-image-9892 aligncenter" title="convariantSubTyping" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/convariantSubTyping1-300x191.png" alt="" width="300" height="191" /></a></p>
<p>Remember that covariant orders types from more <em>specific</em> to more <em>generic</em>.</p>
<p>Let's construct a small investor again with new <span style="text-decoration: underline;">Company</span> definition:</p>
<pre>scala&gt; val smallInvestor:Investor = new Investor(littleCompany)
smallInvestor: Investor = Investor@9fad9c</pre>
<p>Great! We could solve this by Scala variance subtyping. By a single + sign that is called <em>variance annotation</em> you could tell Scala compiler that you want <span style="text-decoration: underline;">Company[SmallCompany]</span> be a subtype of <span style="text-decoration: underline;">Company[BigCompany]</span>.</p>
<p>In the next <a title="post" href="http://blog.jayway.com/2011/10/04/scala-type-variances-part-two/">post</a>, we will investigate contravariant subtyping.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/03/scala-type-variances-part-one/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Experimenting with Scala Parallel Collections</title>
		<link>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/</link>
		<comments>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 15:26:13 +0000</pubDate>
		<dc:creator>Amir Moulavi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9802</guid>
		<description><![CDATA[In this short post, I want to show you how you can avail from Scala parallel collections in your application and under which conditions it makes sense to use it. Parallel Collections were introduced in Scala 2.9 release which are built on the same abstractions and provide the same interfaces as existing collection implementation. It [...]]]></description>
			<content:encoded><![CDATA[<p>In this short post, I want to show you how you can avail from Scala parallel collections in your application and under which conditions it makes sense to use it.</p>
<p>Parallel Collections were introduced in <a title="Scala 2.9" href="http://www.scala-lang.org/node/9483">Scala 2.9</a> release which are built on the same abstractions and provide the same interfaces as existing collection implementation. It follows the model proposed by Doug Lea in his Fork/Join framework [1]. They are really easy to use and this is one of the advantages you can see for them. If you are familiar with parallel programming, it is quite difficult to convert a sequential program into a parallel one. This difficulty comes from the fact that each has its own paradigm, algorithm and data structure.</p>
<p>Scala enables you to invoke a method called <strong>par</strong> on a collection to get a parallel collection. This parallel collection then employs all the available cores on the target system. You can easily try this out in REPL:</p>
<pre>scala&gt; List(1,2,3,4,5).par.filter { _ % 2 == 0 }
res1: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4)</pre>
<p>This is a simple filtering on a list. The only new thing I added is 'par' after list definition.</p>
<p>Now let's have a comparison between sequential and parallel versions and see how parallel collection can help us. Consider that we have a Data class with some data as follows:</p>
<p><script src="https://gist.github.com/1292276.js?file=Data.scala"></script></p>
<p>and a companion object to construct Data instances:</p>
<p><script src="https://gist.github.com/1292276.js?file=CompanionData.scala"></script></p>
<p>Now we define computation trait to perform some operations on the aforementioned data class:</p>
<p><script src="https://gist.github.com/1292276.js?file=Computation.scala"></script></p>
<p>This trait has two implementations:</p>
<p><script src="https://gist.github.com/1292276.js?file=Implementations.scala"></script></p>
<p>In each implementation, method compute applies a map with function f and then calculate the maximum element in the list. The only difference between these two implementations is the use of 'par' method. Now let's run and time each implementation:</p>
<p><script src="https://gist.github.com/1292276.js?file=Experiment.scala"></script></p>
<p>Running the code with SBT on a machine with 4 CPU cores:</p>
<pre>&gt; run 3
[info] Running com.jayway.parallel.ParallelExperiment 3
Sequential 44 (ms)
Parallel 14 (ms)</pre>
<p>&nbsp;</p>
<pre>&gt; run 100
[info] Running com.jayway.parallel.ParallelExperiment 100
Sequential 1020 (ms)
Parallel 268 (ms)</pre>
<p>As expected, we gained speed up in parallel version. Results for a couple of run with different list sizes is depicted in the following fgure:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_htm_88dfb8f1.jpg" rel="lightbox"><img class="aligncenter size-full wp-image-9833" title="parallel-result_htm_88dfb8f" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_htm_88dfb8f1.jpg" alt="" width="580" height="397" /></a></p>
<p>Now let's change function f to the following:</p>
<pre>  def f(data:Data):Int =  {
    data.a + data.b
  }</pre>
<p>I removed the Thread.sleep so the method returns immediately. Now let's have a look at results for different runs again:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_21.jpeg" rel="lightbox"><img class="aligncenter size-full wp-image-9837" title="parallel-result_2" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_21.jpeg" alt="" width="583" height="407" /></a><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/10/parallel-result_2.jpeg"><br />
</a></p>
<p>Interestingly, this time the result is not good at all! It's even vice versa and sequential implementation has lower running time for the first 5 runs. This is because using parallel collection has some overhead for distributing (fork) and gathering (join) the data between cores. Thus one can conclude having heavy computations (which is the case in most applications), parallel collections can be of great performance improvement. But there might be scenarios (like the second scenario we discussed) where sequential collection is faster <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For a better understanding of Scala Parallel Collection internals, please watch <a title="Aleksander Prokopec's presentation" href="http://days2010.scala-lang.org/node/138/140">Aleksander Prokopec's presentation</a> from Scala Days 2010. If you are interested to know more then you can read [2].</p>
<h3>References:</h3>
<p>[1]: Doug Lea, A Java Fork/Join Framework, 2000.<br />
[2]: Aleksandar Prokopec, Tiark Rompf, Phil Bagwell, Martin Odersky, "A Generic Parallel Collection Framework", Euro-Par 2011</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/10/02/experimenting-with-scala-parallel-collections/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Intercepting Scala trait constructors</title>
		<link>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/</link>
		<comments>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 21:40:01 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5430</guid>
		<description><![CDATA[Today I was writing an AspectJ aspect for a Scala trait and was wondering why my constructor pointcut definition didn't work. Having a closer look at the Scala byte code together with my colleague Johan solved the puzzle. Here is what I did (using AspectJ 1.6.8 and Scala 2.8.Beta1): To start with here's a simplified [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was writing an AspectJ aspect for a Scala trait and was wondering why my constructor pointcut definition didn't work. Having a closer look at the Scala byte code together with my colleague Johan solved the puzzle. Here is what I did (using AspectJ 1.6.8 and Scala 2.8.Beta1):</p>
<p>To start with here's a simplified version of the trait that I wanted to intercept:</p>
<pre class="brush:scala">
trait MyTrait {
    var someStuff = "someStuff"
    def someMethod() : String = {
        "do something"
    }
}

class SomeClass extends MyTrait
</pre>
<p>As I wanted to intercept the constructor and some method calls I defined my aspect like this:</p>
<pre class="brush:java">

public aspect MyAspect {

	public pointcut newInstance() : execution(MyTrait+.new(..));

	public pointcut someInvocation() : execution(String MyTrait+.someMethod(..));

	after() : newInstance() {
	    System.out.println("after MyTrait constructor invocation");
	}

	after() : someInvocation() {
	    System.out.println("after someMethod invocation");
	}
}
</pre>
<p>Runnning the code I got quite puzzled that the method invocation pointcut worked fine, but not the constructor pointcut. After consulting the AspectJ reference and convincing myself that the pointcut definition was ok, I had a closer look at the byte code. As we don't have traits in Java the byte code for my trait becomes equivalent to the following pseudo-javacode:</p>
<pre class="brush:java">
public interface MyTrait extends scala.ScalaObject{
    public String someMethod();
}

public abstract class MyTrait$class extends java.lang.Object{
    public static String someMethod(MyTrait myTrait) {
      // invoke someMethod
    }
    public static void $init$(MyTrait myTrait) {
      // some init stuff
    }
}
</pre>
<p>So in bytecode I've got an interface and a class with some static method calls. The stuff that goes in the constructor of my trait is done in the <code>$init$</code> method of the <code>MyTrait$class</code> class. And that's the reason why my pointcut won't work. So actually I have to intercept the <code>$init$</code> method of the <code>MyTrait$class</code> to get what i want:</p>
<pre class="brush:java">
public pointcut newInstance() : execution(void MyTrait$class.$init$(..));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/28/intercepting-scala-trait-constructors/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extending the JDT</title>
		<link>http://blog.jayway.com/2010/04/20/extending-the-jdt/</link>
		<comments>http://blog.jayway.com/2010/04/20/extending-the-jdt/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 21:01:43 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5387</guid>
		<description><![CDATA[A couple of weeks ago I had a look at the Motodevstudio for Android developers and I think it has some quite nice features like code snippets or wizards for Android activities, services and more. Actually it's is quite easy to extend the eclipse JDT and provide such useful plugins. This blog post is about [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I had a look at the <a href="http://developer.motorola.com/docstools/motodevstudio/">Motodevstudio</a> for Android developers and I think it has some quite nice features like code snippets or wizards for Android activities, services and more. Actually it's is quite easy to extend the eclipse JDT and provide such useful plugins. This blog post is about how to extend the NewElementWizard in JDT using eclipse Galileo.  </p>
<p>We start with creating a new eclipse plugin project and create our wizard class. The NewElementWizard we want to extend resides in the <code>org.eclipse.jdt.ui</code> bundle. So we add both <code>org.eclipse.jdt.ui</code> and <code>org.eclipse.jdt.core</code> to our plugin manifest:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Screen-shot-2010-02-28-at-9.53.40-PM.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/Screen-shot-2010-02-28-at-9.53.40-PM-300x234.png" alt="Manifest" title="Manifest" width="300" height="234" class="alignnone size-medium wp-image-5388" /></a></p>
<p>Then we create a new class "NewActivityWizard":</p>
<pre class="brush:java">
package newwizard;

import org.eclipse.jdt.internal.ui.wizards.NewElementWizard;

public class NewActivityWizard extends NewElementWizard {

}
</pre>
<p>First thing we get is a warning<br />
"Discouraged access: The type NewElementWizard is not accessible due to restriction on required library /Applications/eclipse/plugins/org.eclipse.jdt.ui_3.5.1.r351_v20090821-0800.jar".</p>
<p>The NewElementWizard belongs to an internal package and is only exported (using the 'xfriends' directive) to some chosen bundles. So we have the choice to have a look at the code of NewElementWizard and implement our wizard by extending <code>org.eclipse.jface.wizard.Wizard</code> instead, or we could make our plugin a fragment. Fragments are part of the OSGi R4 release and according to the specification a fragment is “a bundle that is attached to a host bundle”, adding content to the target bundle. For now we choose the later alternative, just because it requires less work.</p>
<p>Next thing we have to do is to override some methods of the superclass and of course we want to add our own wizard page. Our wizardpage will extend the <code>org.eclipse.jdt.ui.wizards.NewTypeWizardPage</code>. The following code is pretty much the same as in the wizards used internally in JDT as for example <code>org.eclipse.jdt.internal.ui.wizards.NewClassCreationWizard</code>. </p>
<pre class="brush:java">
public class NewActivityWizard extends NewElementWizard {

	private NewActivityWizardPage newActivityPage = null;

	public NewActivityWizard() {
        setWindowTitle("My new Android Activity");
        newActivityPage = new NewActivityWizardPage();
    }

	@Override
	public void addPages() {
        addPage(newActivityPage);
    }

    @Override
	 public void init(IWorkbench workbench, IStructuredSelection selection) {
    	newActivityPage.init(selection);
    }

    @Override
	public boolean canFinish() {
       return super.canFinish() &&
                   getContainer().getCurrentPage() == newActivityPage;
    }

	@Override
	protected void finishPage(IProgressMonitor monitor)	throws InterruptedException, CoreException {
		newActivityPage.createType(monitor);
	}

	@Override
	public IJavaElement getCreatedElement() {
		return newActivityPage.getCreatedType();
	}
}
</pre>
<p>Next we have to define the extension in the fragment.xml:</p>
<pre class="brush:xml">
 <extension  point="org.eclipse.ui.newWizards">
      <wizard
            canFinishEarly="false"
            category="com.android.ide.eclipse.wizards.category"
            class="newwizard.NewActivityWizard"
            finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
            id="newwizard.NewActivityWizard"
            name="My Android Activity"
            preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
            project="false">
      </wizard>
   </extension>
</pre>
<p>The most interesting part of the wizard page is the code generation part. We want to generate a <code>onCreate</code> method that takes a <code>android.os.Bundle</code> as argument:</p>
<pre class="brush:java">
private void generateOnCreate(IType type, ImportsManager imports) throws CoreException, JavaModelException {
	StringBuilder buf = new StringBuilder();
	final String delim = "\n";
	buf.append("@Override");
	buf.append(lineDelim);
	buf.append("public void onCreate(");
	buf.append(imports.addImport("android.os.Bundle"));
	buf.append(" savedInstanceState) {");
	buf.append(lineDelim);
	buf.append("super.onCreate(savedInstanceState);");
	buf.append(lineDelim);
	final String content =
            CodeGeneration.getMethodBodyContent(type.getCompilationUnit(),
               type.getTypeQualifiedName('.'), "onCreate", false, "", delim);
	if (content != null && content.length() != 0)
		buf.append(content);
	buf.append(lineDelim);
	buf.append("}"); //$NON-NLS-1$
	type.createMethod(buf.toString(), null, false, null);
}
</pre>
<p>This is just the basic version of the new wizard, we also want to add intent actions and categories and update the Android manifest file. The complete source is available at <a href="http://github.com/kobmic/adt-extensions">http://github.com/kobmic/adt-extensions</a>. 	</p>
<p>So how do we update the android manifest? As a Java programmer <a href="http://www.dom4j.org">dom4j</a> and <a href="http://xstream.codehaus.org">XStream</a> are some of my favourite XML frameworks - but I'm quite enthusiastic about Scala and Scala provides XML support baked into the language. The XML generation code for a new Android activtiy with a given list of intent actions and categories in Scala looks like this:</p>
<pre class="brush:scala">
def createXML(activityName: String, intentActions: List[String], intentCategories: List[String]) : Node = {
  val xml =
    <activity android:name={activityName}
      <intent-filter>
         {for(action <- intentActions)
             yield {<action android:name={action} />}}
	 {for(category <- intentCategories)
             yield {<category android:name={category} />}}
      </intent-filter>
    </activity>
   xml
}
</pre>
<h2>Putting it all together</h2>
<p>I chose to do the XML manipulation (written in Scala) and the Wizard (written in Java) in different OSGi bundles. If you don't have the eclipse Scala IDE installed you even need the Scala library 2.7.7 as OSGi bundle. You can download the wizard with or without Scala dependencies from <a href="http://github.com/kobmic/adt-extensions/downloads">http://github.com/kobmic/adt-extensions/downloads</a>. </p>
<p>The complete wizard looks like this:<br />
<a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/new-activity-wizard.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/new-activity-wizard-228x300.png" alt="" title="new-activity-wizard" width="228" height="300" class="aligncenter size-medium wp-image-5389" /></a></p>
<p>At time of writing there's a new version of MOTODEV studio available, now even as a set of plugins to eclipse:<br />
<a href="http://developer.motorola.com/docstools/library/Installing_MOTODEV_Studio_for_Android">http://developer.motorola.com/docstools/library/Installing_MOTODEV_Studio_for_Android/#installingStudioPlugins</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/04/20/extending-the-jdt/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Building OSGi Bundles with Scala and Gradle</title>
		<link>http://blog.jayway.com/2010/02/09/building-osgi-bundles-with-scala-and-gradle/</link>
		<comments>http://blog.jayway.com/2010/02/09/building-osgi-bundles-with-scala-and-gradle/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 19:56:02 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[build systems]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4712</guid>
		<description><![CDATA[There already some good blog posts about how to build OSGi bundles in Scala, among others "An OSGi Bundle… built in Scala" of Neil Bartlett and "OSGi, Maven and Scala" of Gavin Bong using pax-construct. Here is another alternative using Gradle. Gradle is an open-source build system providing the expressiveness of a Groovy based DSL [...]]]></description>
			<content:encoded><![CDATA[<p>There already some good blog posts about how to build OSGi bundles in Scala, among others <a href="http://neilbartlett.name/blog/2007/04/06/an-osgi-bundle-built-in-scala/">"An OSGi Bundle… built in Scala"</a> of Neil Bartlett and <a href="http://www.raverun.com/writings/tech/scalaosgi/">"OSGi, Maven and Scala"</a> of Gavin Bong using pax-construct. Here is another alternative using <a href="http://gradle.org">Gradle</a>. Gradle is an open-source build system providing the expressiveness of a Groovy based DSL together with build-by-convention support for the major build scenarios in the Java/Groovy world. Above that there is even support for Scala.</p>
<p>If you want to follow the example you need:<br />
gradle 0.8<br />
scala 2.7.7<br />
apache felix framework 2.0.1 (or your favourite OSGi container)</p>
<p>Instead of a HelloWorld I'll take Neill's BundleActivator example that prints out a list of currently installed bundles when started.</p>
<pre class="brush:scala">
package com.jayway.osgi.hello

import org.osgi.framework._

class Activator extends BundleActivator {  

    def start( context: BundleContext ) {
          var bundleNames = context.getBundles()
                   .map   (b => b.getSymbolicName())
                   .filter(b => b != context.getBundle())
          println("Installed bundles: " + bundleNames.toString())
     }    

     def stop( context: BundleContext )  {
     }
 }
</pre>
<p>Gradle comes with both Scala and OSGi plugins that make it quite easy to build the bundle. The Scala plugin assumes the same standard project layout as used in Maven, i.e java production code will reside in the 'src/main/java', scala production code in the 'src/main/scala' folder. So I put the Activator class in 'src/main/scala' and add the following build.gradle file in my project folder:</p>
<pre class="brush:groovy">
group = 'com.jayway'
version = '1.0.0'

usePlugin 'scala'
usePlugin 'osgi'

repositories {
  mavenCentral()  // http://repo1.maven.org/maven2/
  mavenRepo(urls: 'http://www.ibiblio.org/maven2/')
  mavenRepo(urls: 'http://scala-tools.org/repo-releases/')
}

dependencies {
    // Libraries needed to run the scala tools
    scalaTools 'org.scala-lang:scala-compiler:2.7.7'
    scalaTools 'org.scala-lang:scala-library:2.7.7'

    compile 'org.scala-lang:scala-library:2.7.7'
    // osgi framework
    compile 'org.apache.felix:org.apache.felix.framework:2.0.1'
}

configure(jar.osgi) {
    // generate the bundle manifest
    version = '1.0.0'
    name = 'scala osgi bundle built with gradle'
    symbolicName = 'com.jayway.osgi.hello'
    instruction 'Require-Bundle', 'scala.library'
    instruction 'Bundle-Activator', 'com.jayway.osgi.hello.Activator'
    instruction 'Import-Package', 'org.osgi.framework'
    instruction 'Export-Package', 'com.jayway.osgi.hello'
    instruction 'Bundle-Vendor', 'JAYWAY AB'
}
</pre>
<p>The Gradle OSGi plugin makes use of the <a href="http://www.aqute.biz/Code/Bnd">BND tool</a> to generate the bundle manifest. I added the scala library OSGi bundle as required and imported the package org.osgi.framework.  Now I'm good to go and call gradle from the commandline:</p>
<pre>
C:\ws-scala-test\com.jayway.osgi.hello>gradle build
</pre>
<h2>Running on apache felix 2.0.1</h2>
<p>Now start the osgi container and install the bundles starting with the scala library as OSGi bundle: </p>
<pre>
C:\felix-framework-2.0.1>java -jar bin/felix.jar

Welcome to Felix
================

->install http://www.scala-lang.org/downloads/distrib/files/scala.library_2.7.7.final.jar
Bundle ID: 24

-> install file:C:\ws-scala-test\com.jayway.osgi.hello\build\libs\com.jayway.osgi.hello-1.0.0.jar
Bundle ID: 25

-> ps
START LEVEL 1
   ID   State         Level  Name
[   0] [Active     ] [    0] System Bundle (2.0.1)
[   1] [Active     ] [    1] Apache Felix Bundle Repository (1.4.2)
[   2] [Active     ] [    1] Apache Felix Shell Service (1.4.1)
[   3] [Active     ] [    1] Apache Felix Shell TUI (1.4.1)
[  24] [Resolved   ] [    1] Scala Library (2.7.7.final)
[  25] [Installed  ] [    1] scala osgi bundle built with gradle (1.0.0)

-> start 25
Installed bundles: Array(org.apache.felix.framework, org.apache.felix.bundlerepository, org.apache.felix.shell, org.apa
he.felix.shell.tui, scala.library, com.jayway.osgi.hello)
</pre>
<h2>Running on eclipse equinox 3.5.1</h2>
<p>If you want to use equinox instead of felix you could change the dependencies like this:</p>
<pre class="brush:groovy">
compile 'org.eclipse:osgi:3.5.1-R35x_v20090827'
</pre>
<p>I had some problems to find a maven repository containing the current equinox osgi bundles (3.5.1). If you are running maven you can publish the bundles from your eclipse installation to your local maven repository:</p>
<pre>
mvn eclipse:to-maven -DeclipseDir="[eclipse-installation-dir]"
</pre>
<p>Finally add your local repository to your build.gradle:</p>
<pre class="brush:groovy">
mavenRepo(urls: 'file://[path-to-user-home]/.m2/repository/')
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/02/09/building-osgi-bundles-with-scala-and-gradle/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting around static typing in Scala</title>
		<link>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/</link>
		<comments>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 19:43:12 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4503</guid>
		<description><![CDATA[I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. ]]></description>
			<content:encoded><![CDATA[<p>I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. I've run the following code in Scala 2.8</p>
<pre class="brush:scala">
// this is easy since everything are Strings
scala> List("one", "two", "three")
res0: List[java.lang.String] = List(one, two, three)

scala> res0.foreach(x => println(x.length()))
3
3
5

// with a mixed collection it gets harder
scala> List("one", 2, "three", 4.0)
res2: List[Any] = List(one, 2, three, 4.0)

scala> res2.foreach(x => println(x.length()))
&lt;console&gt;:6: error: value length is not a member of Any

// it is not enough to just filter out the objects that are Strings
scala> res2.filter(_.isInstanceOf[String])
res4: List[Any] = List(one, three)

// as we still have a List of Any
scala> res4.foreach(x => println(x.length()))
&lt;console&gt;:7: error: value length is not a member of Any

// both filtering and mapping is needed
scala> res2.filter(_.isInstanceOf[String]).map(_.asInstanceOf[String])
res6: List[String] = List(one, three)

// finally it works
scala> res6.foreach(x => println(x.length()))
3
5

// another option is to use pattern matching
scala> res2.foreach(_ match { case x:String => println(x.length); case _ => })
3
5
</pre>
<p>I wanted a more elegant solution with less boiler plate so after playing around with <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766">implicit conversions</a> and <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types</a> I managed to come up with rather nice solution:</p>
<pre class="brush:scala">
// define a class that implements a restrictTo method
scala> class IterableWithRestrictTo[A](from:Iterable[A]) {
     | def restrictTo[B](implicit m: scala.reflect.Manifest[B]) = {
     | from.filter(m.erasure.isInstance(_)).map(_.asInstanceOf[B])
     | }
     | }
defined class IterableWithRestrictTo

// define implicit conversion
scala> implicit def makeIterableWithRestrictTo[A](from : Iterable[A]) = {
     | new IterableWithRestrictTo(from)
     | }
makeIterableWithRestrictTo: [A](from: Iterable[A])IterableWithRestrictTo[A]

scala> List("one", 2, "three", 4.0)
res0: List[Any] = List(one, 2, three, 4.0)

// restrict to objects of type String
scala> res0.restrictTo[String]
res1: Iterable[String] = List(one, three)

// works since the collection have correct type
scala> res1.foreach(x => println(x.length()))
3
5
</pre>
<p>Using the name restrictTo clearly shows that not only is there a type conversion, but also a restriction to a subset of the elements. Notice that the manifest is needed to get the reified type, since the type B is actually erased at compile time. Read more about <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types in Scala</a>.</p>
<p>Let me know you have another solution! </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Golden Ratio</title>
		<link>http://blog.jayway.com/2009/10/24/the-golden-ratio/</link>
		<comments>http://blog.jayway.com/2009/10/24/the-golden-ratio/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 21:40:53 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[goldenratio]]></category>
		<category><![CDATA[mathematics]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2139</guid>
		<description><![CDATA[Also known as the "Divine Quotient", the Golden Ratio was given an almost magical meaning during the renaissance, but it's actually much older than that. Leonardo DaVinci used it. Euclid used it. It was supposedly discovered by Pythagoras. So, what is it? It's very simple. Take a length and divide it into two parts: a [...]]]></description>
			<content:encoded><![CDATA[<p>Also known as the "Divine Quotient", the Golden Ratio was given an almost magical meaning during the renaissance, but it's actually much older than that. Leonardo DaVinci used it. Euclid used it. It was supposedly discovered by Pythagoras. So, what is it? It's very simple. Take a length and divide it into two parts: <code>a</code> and <code>b</code>:
</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/6/65/Image-Golden_ratio_line.png" /></p>
<p>
When the ratio between <code>a</code> and <code>b</code> is equal to the ratio between <code>a+b</code> and <code>a</code>, then you have the Golden Ratio. The value of the Golden Ratio is:
</p>
<p><img src="http://upload.wikimedia.org/math/a/3/d/a3d3da4fbbcb7bfb997c5f480ad905bd.png" /></p>
<p>Why is it so special? Because if you know about it, it can be seen in many different places; in geometrical figures, in architecture, in paintings, and in nature. I'll show you. Draw a pentagon:
</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagon.png" alt="Pentagon" title="pentagon" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>Draw straight lines between all vertices of the pentagon. This will result in a pentagram (five-pointed star). Now mark the lengths <code>a</code> and <code>b</code> as this picture shows:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagram_lengths.png" alt="Pentagram inside pentagon" title="pentagram with lengths" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>Guess what the ratio is between the lengths <code>a</code> and <code>b</code>? The Golden Ratio. Now, mark two other lengths <code>a'</code> and <code>b'</code>:</p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/10/pentagram_lengths2.png" alt="Pentagram inside pentagon with other lengths" title="pentagram with other lengths" width="382" height="364" class="size-full wp-image-2154" /></p>
<p>You guessed it. The ratio between <code>a'</code> and <code>b'</code> is the Golden Ratio.</p>
<p>It's actually pretty easy to approximate Phi (<em>&#x03C6;</em>), as the Golden Ratio normally is called. Take any two numbers and add them, then divide the sum with the larger number. For example, 11 and 74:
</p>
<pre>
11.0+74.0=85.0
85.0/74.0=1.1486486486486487
</pre>
<p>Now we add the larger of the numbers (74) to the sum (85), and then we again divide the new sum (159) with the the previous sum (85):
</p>
<pre>
74.0+85.0=159.0
159.0/85.0=1.8705882352941177
</pre>
<p>We're getting there. One more time:</p>
<pre>
85.0+159.0=244.0
244.0/159.0=1.5345911949685536
</pre>
<p>No, this is too tedious. Let's write a program that does it. For no reason whatsoever, I'll pick Scala. What is Scala? I'm on a Mac, so I'll just do:</p>
<pre>
% port info scala
scala @2.7.5 (lang, java)

Description:          Scala is a modern multi-paradigm programming language designed to express common programming patterns
                      in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and
                      functional languages. It runs inside a Java Virtual Machine and is fully interoperable with Java.
Homepage:             http://www.scala-lang.org/
</pre>
<p>This is how I install Scala:</p>
<pre>
% sudo port install scala
</pre>
<p>I'll want some editor support, so I install the TextMate bundle that accompanies Scala:</p>
<pre>
% cd /Library/Application\ Support/TextMate/Bundles/
% unzip /opt/local/share/scala/misc/scala-tool-support/textmate/Bundles/Scala.tmbundle.zip
</pre>
<p>I'll tell TextMate to reload its bundles by selecting the menu "Bundles | Bundle Editor | Reload Bundles". Now I'm all set.</p>
<p>Consider this Scala program (phi1.scala):</p>
<pre>
var x = 11.
var y = 74.

for (i &lt;- 1 to 5) {
    var sum = x + y
    var q = sum / y
    println(q)
    x = y
    y = sum
}
</pre>
<p>I'll run it like this:</p>
<pre>
% scala phi1.scala
1.1486486486486487
1.8705882352941177
1.5345911949685536
1.651639344262295
1.6054590570719602
</pre>
<p>It's not pretty, but it does the job. Let's spice it up with some input arguments and better printout (phi2.scala):</p>
<pre>
var x = 11.
var y = 74.
var n = 13

if (args.length &gt; 3) {
    println(&quot;Usage: scala phi2.scala [n [x [y]]]&quot;)
    println(&quot;  n: number of times to perform calculation (default: &quot; + n + &quot;)&quot;)
    println(&quot;  x: start value of &#x27;x&#x27; (default: &quot; + x + &quot;)&quot;)
    println(&quot;  y: start value of &#x27;y&#x27; (default: &quot; + y + &quot;)&quot;)
    System.exit(1)
}
if (args.length &gt;= 1) n = Integer.parseInt(args(0))
if (args.length &gt;= 2) x = Integer.parseInt(args(1))
if (args.length == 3) y = Integer.parseInt(args(2))

for (i &lt;- 1 to n) {
    var sum = x + y
    print(i + &quot;: &quot; + x + &quot;+&quot; + y + &quot;=&quot; + sum)
    var q = sum / y
    println(&quot;, &quot; + sum + &quot;/&quot; + y + &quot;=&quot; + q)
    x = y
    y = sum
}
</pre>
<p>I'll run it with four arguments to test it:</p>
<pre>
% scala phi2.scala 1 2 3 4
Usage: scala phi2.scala [n [x [y]]]
  n: number of times to perform calculation (default: 13)
  x: start value of 'x' (default: 11.0)
  y: start value of 'y' (default: 74.0)
</pre>
<p>I won't bore you with more tests, but instead do what we intended to do from the start: have a program run the iterations for us. I'll run it with no arguments, using the defaults:</p>
<pre>
% scala phi2.scala
1: 11.0+74.0=85.0, 85.0/74.0=1.1486486486486487
2: 74.0+85.0=159.0, 159.0/85.0=1.8705882352941177
3: 85.0+159.0=244.0, 244.0/159.0=1.5345911949685536
4: 159.0+244.0=403.0, 403.0/244.0=1.651639344262295
5: 244.0+403.0=647.0, 647.0/403.0=1.6054590570719602
6: 403.0+647.0=1050.0, 1050.0/647.0=1.6228748068006182
7: 647.0+1050.0=1697.0, 1697.0/1050.0=1.6161904761904762
8: 1050.0+1697.0=2747.0, 2747.0/1697.0=1.618738951090159
9: 1697.0+2747.0=4444.0, 4444.0/2747.0=1.6177648343647615
10: 2747.0+4444.0=7191.0, 7191.0/4444.0=1.618136813681368
11: 4444.0+7191.0=11635.0, 11635.0/7191.0=1.6179947156167431
12: 7191.0+11635.0=18826.0, 18826.0/11635.0=1.6180489901160293
13: 11635.0+18826.0=30461.0, 30461.0/18826.0=1.6180282587910337
</pre>
<p>Actually, I will run one more test, but this time I'll choose the starting values more carefully. One of many wonderful properties of the <a href="http://en.wikipedia.org/wiki/Fibonacci">Fibonacci</a> series is that the ratio between the numbers is very close to the Golden Ratio. This means it will converge much quicker. Check this out, four correct decimals after just four iterations:
</p>
<pre>
% scala phi2.scala 4 21 34
1: 21.0+34.0=55.0, 55.0/34.0=1.6176470588235294
2: 34.0+55.0=89.0, 89.0/55.0=1.6181818181818182
3: 55.0+89.0=144.0, 144.0/89.0=1.6179775280898876
4: 89.0+144.0=233.0, 233.0/144.0=1.6180555555555556
</pre>
<p>Here is the final version, with some stuff that makes the file executable (phi.scala):
</p>
<pre>
#!/bin/sh
exec scala $0 $@
!#
var x = 11.
var y = 74.
var n = 13

if (args.length &gt; 3) {
    println(&quot;Usage: scala phi.scala [n [x [y]]]&quot;)
    println(&quot;  n: number of times to perform calculation (default: &quot; + n + &quot;)&quot;)
    println(&quot;  x: start value of &#x27;x&#x27; (default: &quot; + x + &quot;)&quot;)
    println(&quot;  y: start value of &#x27;y&#x27; (default: &quot; + y + &quot;)&quot;)
    System.exit(1)
}
if (args.length &gt;= 1) n = Integer.parseInt(args(0))
if (args.length &gt;= 2) x = Integer.parseInt(args(1))
if (args.length == 3) y = Integer.parseInt(args(2))

for (i &lt;- 1 to n) {
    var sum = x + y
    print(i + &quot;: &quot; + x + &quot;+&quot; + y + &quot;=&quot; + sum)
    var q = sum / y
    println(&quot;, &quot; + sum + &quot;/&quot; + y + &quot;=&quot; + q)
    x = y
    y = sum
}
</pre>
<p>I'll make it executable and run it:</p>
<pre>
% chmod +x phi.scala
% ./phi.scala 10 13 21
1: 13.0+21.0=34.0, 34.0/21.0=1.619047619047619
2: 21.0+34.0=55.0, 55.0/34.0=1.6176470588235294
3: 34.0+55.0=89.0, 89.0/55.0=1.6181818181818182
4: 55.0+89.0=144.0, 144.0/89.0=1.6179775280898876
5: 89.0+144.0=233.0, 233.0/144.0=1.6180555555555556
6: 144.0+233.0=377.0, 377.0/233.0=1.6180257510729614
7: 233.0+377.0=610.0, 610.0/377.0=1.6180371352785146
8: 377.0+610.0=987.0, 987.0/610.0=1.618032786885246
9: 610.0+987.0=1597.0, 1597.0/987.0=1.618034447821682
10: 987.0+1597.0=2584.0, 2584.0/1597.0=1.6180338134001253
</pre>
<p>Check out <a href="http://en.wikipedia.org/wiki/Golden_ratio">Golden Ratio</a> on Wikipedia for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/24/the-golden-ratio/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scala IDE support</title>
		<link>http://blog.jayway.com/2009/03/12/scala-ide-support/</link>
		<comments>http://blog.jayway.com/2009/03/12/scala-ide-support/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 07:14:47 +0000</pubDate>
		<dc:creator>Michael Kober</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1033</guid>
		<description><![CDATA[Today we wanted to test the scala java interoperabilty in different IDEs. We used the Scala plugin for Eclipse, Netbeans and IntelliJ. The intellij plugin worked out of the box. We managed to get the eclipse plugin working after some trouble as well. Although the netbeans plugin seems promising the interoperability between java and scala [...]]]></description>
			<content:encoded><![CDATA[<p>Today we wanted to test the scala java interoperabilty in different IDEs. We used the Scala plugin for Eclipse, Netbeans and IntelliJ. The intellij plugin worked out of the box. We managed to get the eclipse plugin working after some trouble as well. Although the netbeans plugin seems promising the interoperability between java and scala projects did not work.</p>
<p>The <a href="http://www.scala-lang.org/node/94">eclipse plugin</a> has pretty basic support for code completion, syntax highlihting, and some wizards to create projects, scala classes, objects and traits.<br />
We started out with one java project and one scala project. Testing with the latest release, it was a bit tricky to resolve our imported java classes at build and runtiime and vice versa:</p>
<p>To use a Scala class in your Java project:</p>
<ul>
<li>add the scala project to the build path of your java project (project properties -&gt; Java Build Path -&gt; Projects -&gt; Add...)</li>
<li>add the scala nature to your java project (rightclick your java project -&gt; Scala -&gt; add Scala nature)</li>
</ul>
<p>To use a Java class in your Scala project:</p>
<ul>
<li>import of java.* works fine (for example using java.util.Date in scala, like in the<a href="http://www.scala-lang.org/docu/files/ScalaTutorial.pdf"> Scala Tutorial for Java programmers</a>)</li>
<li>add the java project to the build path of your scala project</li>
</ul>
<p>With the current eclipse plugin it is not possible to use scala objects in your java classes. This seems to be a known issue.</p>
<p>It's even possible to create scala and java classes in the same project if your project has both scala and java nature. But the mixed project support in the plugin is still quite buggy: adding a java class to your scala project sometimes make eclipse think that your scala class is a java class. Closing and reopening your project is a way to get around this.</p>
<p>Overall working with the scala eclipse plugin is quite frustating, as it is still very buggy. Actually the first impression was that interoperability does not work at all in the plugin.</p>
<p>The <a href="http://www.jetbrains.net/confluence/display/SCA/Scala+Plugin+for+IntelliJ+IDEA">IntelliJ Scala plugin</a> 0.2.22340 had much better Scala support with all the above and then refactoring support (rename, move, introduce variable) and open declaration navigation. IntelliJ also supported Java and Scala interoperability even within the same module.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/12/scala-ide-support/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Azul</title>
		<link>http://blog.jayway.com/2008/10/20/azul/</link>
		<comments>http://blog.jayway.com/2008/10/20/azul/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 19:58:46 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=363</guid>
		<description><![CDATA[We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly. Read more...]]></description>
			<content:encoded><![CDATA[<p>We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly.</p>
<p>Here is screenshot from the management console showing 81 active CPUs and 23 GB free memory:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" alt="" title="azul" width="600" height="250" class="alignnone size-medium wp-image-364" /></a></p>
<p>I tried some <a href="http://www.scala-lang.org/node/242">Scala actors</a> which worked very well. By running some CPU intensive calculations I concluded that it scaled linearly up to the number of CPUs. No surprise, but very cool when you are running 80 threads at full speed! Also cool to see that Scala runs smoothly which means that neither Scala nor Azul does anything strange. Just pure bytecode.</p>
<p>Somebody tried to configure the Azul JVM in Eclipse and was able to run JUnit tests on Azul. We were also able to run maven without any problems.</p>
<p>We tried to allocate lots of memory. No problem there either, although we had to specify -Xmx10G or something. By default you only get 1.6 GB....</p>
<p>A colleague started tomcat, produced lots of garbage and tried garbage collection at 8 GB of heap. No pause! However, there was some synchronization problem with Log4j since all 16 CPUs had to coordinate their work.</p>
<p>We encountered two problems:</p>
<ul>
<li>xstream apparently had a dependency to Unsafe which is not supported on Azul</li>
<li>the program must be headless, so no Swing</li>
</ul>
<p>A quick rewrite later and we had generated a 64 megapixel mandelbrot calculated in parallel on 40 CPUs. The only problem was saving the PNG file which was a single threaded operation...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/azul/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

