<?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>JavaBeat &#187; Scala</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/scala-web-frameworks/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Playing with reduceLeft, reduceRight, foldLeft, foldRight API in Scala</title>
		<link>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/</link>
		<comments>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/#comments</comments>
		<pubDate>Wed, 18 Jul 2012 18:21:40 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4749</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous post we saw in detail about the foreach. map, flatMap and collect methods in the Iterable trait. In this post we will look into detail about reduceLeft, reduceRight, foldLeft, foldRight methods of the Iterable trait. These methods are almost similar in the way the operate on the collection so it should be [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>In our <a href="http://www.javabeat.net/2012/07/playing-with-collections-api-in-scala/" title="Playing with Collections API in Scala">previous post</a> we saw in detail about the foreach. map, flatMap and collect methods in the Iterable trait. In this post we will look into detail about reduceLeft, reduceRight, foldLeft, foldRight methods of the Iterable trait. These methods are almost similar in the way the operate on the collection so it should be easier to study them together. </p>
<p><strong>reduceLeft/reduceRight:</strong> The scala doc declares this method as:</p>
<pre class="brush: java; title: ; notranslate">reduceLeft[B &gt;: A](op: (B, A) ⇒ B): B</pre>
<p>which means that this method accepts a function which takes in 2 parameters and returns one value. And the way this method works is that it applies the operation/passed function on 2 elements at a time starting from left, and result of each application is used to compare with the next element until the end of list.<br />
Lets use this reduceLeft to find out the largest and smallest elements in the collection of numbers:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.reduceLeft((x,a) =&gt; if ( x &lt; a ) a else x)
res86: Int = 42
//smallest element
scala&gt; numbers.reduceLeft((x,a) =&gt; if ( x &lt; a) x else a)
res87: Int = 2
</pre>
<p>reduceRight is exactly similar to reduceLeft the only different being reduceRight applies the operation/passed function on the elements starting from the right of the list. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
scala&gt; val numbers = List(4,21,2,4,62,345,67)
numbers: List[Int] = List(4, 21, 2, 4, 62, 345, 67)

//finding maximum
scala&gt; numbers.reduceRight((x,v) =&gt; if (x &gt; v) x else v)
res0: Int = 345

//finding minimum
scala&gt; numbers.reduceRight((x,v) =&gt; if (x &lt; v) x else v)
res1: Int = 2
</pre>
<p><strong>foldLeft/foldRight:</strong> Exactly similar to the way reduceLeft/reduceRight work with a slight difference being foldLeft/foldRight take in an initial value and then apply the initial value to the first element(either leftmost/rightmost) before proceeding like reduceLeft/reduceRight.<br />
Suppose we want to find the sum of the elements in a list (I can use the &#8220;sum&#8221; method directly, but for understanding I would use  foldLeft/reduceLeft):</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val numbers = List(1,2,3,4,5,6,7,8,9,10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
//initial seed value of 0 gave the correct sum
scala&gt; numbers.foldLeft(0)((sum,x) =&gt; sum + x)
res0: Int = 55

//initial seed value of 10 added 10 to the final sum.
scala&gt; numbers.foldLeft(10)((sum,x) =&gt; sum + x)
res1: Int = 65
</pre>
<p>One another use of foldLeft is to find the factorial:</p>
<pre class="brush: java; title: ; notranslate">
//factorial of 5
scala&gt; 1.to(5).foldLeft(1)((prod,x)=&gt;prod*x)
res3: Int = 120

//factorial of 6
scala&gt; 1.to(6).foldLeft(1)((prod,x)=&gt;prod*x)
res4: Int = 720
</pre>
<p><strong>scanLeft/scanRight:</strong> It functions exactly similar to foldLeft/foldRight, but instead of returning one value these methods return a collection of values. These collection of values are nothing but the intermediate values obtained while the passed function was applied on the list of numbers.<br />
Lets look at the same factorial example using scanLeft/scanRight:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; 1.to(6).scanLeft(1)((prod,x)=&gt;prod*x)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 1, 2, 6, 24, 120, 720)

scala&gt; 1.to(6).scanRight(1)((prod,x)=&gt;prod*x)
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 6, 30, 120, 360, 720, 720)
</pre>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fscala-web-frameworks%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/scala-web-frameworks/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/scala-web-frameworks/feed/" data-count="vertical" data-text="Scala" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Playing with Collections API in Scala</title>
		<link>http://www.javabeat.net/2012/07/playing-with-collections-api-in-scala/</link>
		<comments>http://www.javabeat.net/2012/07/playing-with-collections-api-in-scala/#comments</comments>
		<pubDate>Sun, 15 Jul 2012 19:27:42 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4744</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>While I was going through the Scala collections API, I found the mere reading through the method and its functionality is not going to help. And I also realised that it will be useful if I can document them. And with that idea, I will try to document the APIs which I have tried. Please [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>While I was going through the Scala collections API, I found the mere reading through the method and its functionality is not going to help. And I also realised that it will be useful if I can document them. And with that idea, I will try to document the APIs which I have tried. Please feel free to suggest more examples and also corrections where ever necessary. I would be using a <a href="http://www.scala-lang.org/api/current/scala/collection/immutable/List.html" target="_blank">List</a> for all the methods.</p>
<p>In all the subsequent examples I would be using the REPL (Read Evaluate Print Loop) tool for running the commands which can be invoked by running the scala command from the command line. </p>
<h4>map, foreach, flatMap, collect:</h4>
<p>defining a List:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val numbers = List(2,3,4,5,6,7,23,42,34)
numbers: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)
</pre>
<p>All the collection classes in Scala extend the <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Iterable" target="_blank">Iterable</a> trait and right through this post we will keep that API doc page open as we would repeatedly refer to it. </p>
<p>foreach: This methods iterates over the elements in the collection and applies the function passed to the foreach method. There&#8217;s another version of foreach method in which the function passed can return a value. But effectively the return value of the function is neglected. The function should be of form: (param) =&gt; {block} (we can make this more concise, I will show in the example)</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.foreach((x) =&gt; {print(x+&quot; &quot;)})
2 3 4 5 6 7 23 42 34
scala&gt; numbers.foreach(x =&gt; print(x+&quot; &quot;))
2 3 4 5 6 7 23 42 34
</pre>
<p>You use this when you want to iterate over the collection and perform some operation on the elements.</p>
<p><strong>map</strong>: This is iterates over the collection but is different from foreach in the way that this generates a new collection from the existing collection by applying the passed function to each element of the collection. Suppose I want to create a List with elements twice the original elements:</p>
<pre class="brush: java; title: ; notranslate">

scala&gt; numbers.map((x)=&gt; x+2)
res69: List[Int] = List(4, 5, 6, 7, 8, 9, 25, 44, 36)

scala&gt; numbers
res70: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

</pre>
<p>In the Scala Doc the map method is declared as: </p>
<pre class="brush: java; title: ; notranslate">
map[B](f: (A) ⇒ B): Iterable[B]
</pre>
<p>and it clearly says that it accepts a function which takes in one parameter(the type of which is the type of the elements of the list) and returns another value whose type can be different. And map method overall returns an Iterable which contains elements whose type is the type of the return values of the function passed. Confusing? Lets look at another example. Our original list is list of Int, but we will generate another list of Double values:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.map(_ + 1.5)
res71: List[Double] = List(3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 24.5, 43.5, 35.5)
</pre>
<p>&#8220;_&#8221; represents the parameter value passed to the function which in this case is an Int. But map method returns a list of Double and our function passed also returns Double value. In all these above operations, the original list didn&#8217;t get modified. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><strong>flatMap</strong>: There&#8217;s a slight twist in this method. The Scala doc declares this method as: <strong>flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Iterable[B]</strong>. This does the same task as that of map method- create a new list by applying the function passed on each element of the list. But the function passed to map would return just one value, but in the flatMap method, the function passed should return an instance of type <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.GenTraversableOnce" target="_blank">GenTraversableOnce</a> which contains some elements of type B. So the overall return type of the flatMap is a Iterable[B] which is nothing but a collection which contains elements of type B. Time for a quick example:</p>
<pre class="brush: java; title: ; notranslate">
//Acts like a map
scala&gt; numbers.flatMap(x =&gt; List(x+2))
res73: List[Int] = List(4, 5, 6, 7, 8, 9, 25, 44, 36)

scala&gt; numbers
res74: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala&gt; numbers.flatMap(x =&gt; List(x,x+2))
res75: List[Int] = List(2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 23, 25, 42, 44, 34, 36)

</pre>
<p>in the 2nd use of flatMap method we pass a function which returns a List of 2 elements for each element in the numbers list, which means the resultant list would have 2 elements for each element in the original list = twice the number of elements in the &#8220;numbers&#8221; list. We can return a List instance from the function passed to the map method, but the map method doesn&#8217;t flatten the return values to form one collection, the below example would clear this:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.map(x =&gt; List(x,x+2))
res84: List[List[Int]] = List(List(2, 4), 
       List(3, 5), List(4, 6), List(5, 7), 
       List(6, 8), List(7, 9), List(23, 25), 
       List(42, 44), List(34, 36))
</pre>
<p>so you see that in case of flatMap, it flattens the each returned list into one common List, but the map method creates a List of Lists. </p>
<p><strong>collect</strong>: This took some time for me to understand. One has to know about <a href="http://www.scala-lang.org/api/current/index.html#scala.PartialFunction" target="_blank">Partial Functions</a> before diving into understanding this method. Partial Functions are different from the <a href="http://blog.sanaulla.info/2010/12/25/partially-applied-functions-in-scala/" target="_blank">partially applied functions</a>. Partial Functions are those functions which are defined for certain parameter values from within the range for the given type i.e if the Parameter for the PartialFunction is Int, then it can be defined for few values from the range of values an Int can take. </p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val partial1:PartialFunction[Int,Int] = { case 1 =&gt; 12}
partial1: PartialFunction[Int,Int] = &lt;function1&gt;

scala&gt; partial1.isDefinedAt(1)
res76: Boolean = true

scala&gt; partial1.isDefinedAt(2)
res77: Boolean = false
</pre>
<p>the above partial function is defined only for 1. Partial functions can be combined using orElse. For more details on Partial Functions, I would recommend the examples <a href="http://twitter.github.com/scala_school/pattern-matching-and-functional-composition.html" target="_blank">here</a>.</p>
<p>The collect method applies the partial function on each element of the list and constructs a new collection from the return values on application of partial function. An example for this would be to return words representation if the element of the list is 1/2/3.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val oneTwoThree:PartialFunction[Int,String] = {case x if x == 1 =&gt; &quot;One&quot;
     | case x  if x == 2 =&gt; &quot;Two&quot;
     | case x if x == 3 =&gt; &quot;Three&quot;
     | }
oneTwoThree: PartialFunction[Int,String] = &lt;function1&gt;

scala&gt; numbers
res78: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala&gt; numbers.collect(oneTwoThree)
res79: List[String] = List(Two, Three)
</pre>
<p>One can see that on applying the partial function using the collect method the resultant is a List[String].<br />
Lets look at another example to just get the even numbers from the list:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers
res80: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala&gt; val isEven:PartialFunction[Int,Int] = { case x if x % 2 == 0 =&gt; x}
isEven: PartialFunction[Int,Int] = &lt;function1&gt;

scala&gt; numbers.collect(isEven)
res81: List[Int] = List(2, 4, 6, 42, 34)
</pre>
<p>One might wonder that the same can be achieved using map, but in cases where the elements dont satisfy the condition we get some empty value, but in collect we dont get any output if the element doesn&#8217;t satisfy the condition. For example, let me just use map method to implement the above:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.map((x)=&gt; if ( x % 2 == 0) x)
res82: List[AnyVal] = List(2, (), 4, (), 6, (), (), 42, 34)

</pre>
<p>one can see that in cases where the elements of the collection didn&#8217;t satisfy the condition there was an empty value returned. </p>
<p>These are just 4 of the many available methods for collections in Scala. In future posts I will show some examples with the other methods. Now that you have got an idea of how to understand the documentation and use these methods, rest of the method should be easy to understand. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/playing-with-collections-api-in-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Functions as First Class Citizens in Scala</title>
		<link>http://www.javabeat.net/2012/07/functions-as-first-class-citizens-in-scala/</link>
		<comments>http://www.javabeat.net/2012/07/functions-as-first-class-citizens-in-scala/#comments</comments>
		<pubDate>Wed, 11 Jul 2012 14:14:29 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4680</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In Java (Java 7 and before) we can store an object reference in a variable or some primitive value in which case Classes and Primitive types are the first class citizens there, but in Scala we can assign method/function definitions to variables, we can pass around function definitions to other functions and we can even [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In Java (Java 7 and before) we can store an object reference in a variable or some primitive value in which case Classes and Primitive types are the first class citizens there, but in Scala we can assign method/function definitions to variables, we can pass around function definitions to other functions and we can even declare functions within fuctions (i.e private functions).</p>
<p>In this small article I will show you how to:</p>
<ol>
<li>Assign functions to variables also called <strong>Function Values</strong></li>
<li>Pass functions as arguments to other functions. The functions which accept other functions as parameters are called <strong>Higher Order Functions</strong>.</li>
<li>Parameter Inference while using Higher Order functions</li>
<li>Currying- which in short is a function which returns another function</li>
<li>Some common higher order functions in Scala collections API</li>
</ol>
<h4>Function Values</h4>
<p>Lets see how we can assign a function definition to variable:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val doubleNumber = (x:Int) =&gt; x * 2
doubleNumber: (Int) =&gt; Int =
</pre>
<p>The above code was executed in the REPL shell (Read Evaluate Print Loop) which can be accessed by running the command: <strong>scala</strong>. We can see that the variable doubleNumber is assigned a function which takes an Int and returns another Int. Anything to the left of <strong>=&gt;</strong> are arguments to the function block and anything to the right of <strong>=&gt;</strong> is the function block which would use the values passed as parameters or can even access values defined outside the block (in which case the function is said to close over that variable also called as closures). Invoking the above method is simple:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; println(doubleNumber(7))
14
</pre>
<p>We can also make use of the variables declared outside of the function block, in which case the function value becomes a <strong>closure</strong>. Such a way of referring to the variables from outside the function block is really powerful. Java programmers are aware of Anonymous Inner classes not able to capture the variables outside of their class definition other than the variable which are declared as final. This restriction is being removed in <a href="http://www.javabeat.net/category/java-8-0/" target="_blank">Java 8</a>.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val increaseByAFactor = (x: Int) =&gt; x * factor
:5: error: not found: value factor
       val increaseByAFactor = (x: Int) =&gt; x * factor
                                               ^
</pre>
<p>the error above is because the function value refers to factor which is not declared before.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; var factor = 3
factor: Int = 3

scala&gt; val increaseByAFactor = (x: Int) =&gt; x * factor
increaseByAFactor: (Int) =&gt; Int =
</pre>
<p>now invoking the function value we have:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; println(increaseByAFactor(4))
12
</pre>
<p>We can even update the function value to take in two parameters- one the value to increment and the other the factor by which to increment.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val increaseByFactor = (x:Int, factor:Int) =&gt; x * factor
increaseByFactor: (Int, Int) =&gt; Int =

scala&gt; println(increaseByFactor(4,2))
8
</pre>
<p>Another term associated with Function Value is <strong>Function Literal</strong>. The function: <strong>(x:Int, factor:Int) =&gt; x * factor</strong> is called as function literal and when assigned to a variable these are together called function values.</p>
<p>Lets dig into how scala compiler handles these function values. For that we would have to compile the above code into bytecode:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends Application{
  val doubleNumber = (x:Int, factor:Int) =&gt; 2 * factor

  println(doubleNumber(2,3))
}
</pre>
<p>Once compiled we would have: Main$$anonfun$1.class, Main$.class, Main.class. Inspecting Main.class one of the entries there is:</p>
<pre class="brush: java; title: ; notranslate">
 public static final scala.Function2 doubleNumber();
</pre>
<p>which shows that the doubleNumber function value is actually converted to a method call doubleNumber() which returns an instance of Function2 class. The Function2 is for function values which take in 2 parameter, if the function value takes one parameter then Function1 instance is created. These FunctionN classes have an apply method which takes these 2 parameters and then perform the operation specified in the function literal.</p>
<h4>Higher Order Functions</h4>
<p>We would declare a function which takes 2 integer- the lower limit and higher limit and another function which is applied to each integer between the lower and higher integers. Such a function we call it as <strong>Higher Order Function</strong> because it takes in other function as a parameter or can return another function as a return value.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; def performOnRange(low:Int, high:Int, func:Int=&gt;Int){
     | low.to(high).foreach(x=&gt; println(func(x)))
     | }
performOnRange: (low: Int,high: Int,func: (Int) =&gt; Int)Unit
</pre>
<p>Here performOnRange is a higher order function. We can define a function value which would be passed to performOnRange:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; var factor = 5
factor: Int = 5

scala&gt; val incrByFact = (x:Int) =&gt; x*factor
incrByFact: (Int) =&gt; Int =
</pre>
<p>and then invoke the performOnRange as below:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; performOnRange(1,5,incrByFact)
5
10
15
20
25
</pre>
<p>We could have directly passed the function literal to the performOnRange, something like:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
scala&gt; performOnRange(1,5, (x:Int) =&gt; x * factor)
5
10
15
20
25
</pre>
<p>which can be further shortened to:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; performOnRange(1,5, _ * factor)
5
10
15
20
25
</pre>
<p>where each <strong>_</strong> stands for a different parameter. In this case we had only on parameter to the function literal and hence only one <strong>_</strong>.</p>
<h4>Common Higher Order Functions in Scala collections</h4>
<p>Scala collections API supports the use of higher order functions for operating on the collection data and what&#8217;s good about this is that the call to the to APIs can be chained something like collection.method1(function1).method2(function2). A good news for Java developers is that the same feature is being implemented in <a href="http://www.javabeat.net/category/java-8-0/" target="_blank">Java 8</a> collections API.</p>
<p>Lets look at few examples:<br />
Finding out the highest number from the array of numbers:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; var numbers = List(3,4,561,2,587,34,23)
numbers: List[Int] = List(3, 4, 561, 2, 587, 34, 23)

scala&gt; numbers.reduceLeft((x:Int,y:Int) =&gt; if ( x &lt; y ) y else x) res6: Int = 587 </pre>
<p>reduceLeft applies the function passed for each element of the array from the left i.e ((((((3,4),561),2),587),34),23). we can make use of parameter inference and then skip the type information for the parameters as:</p>
<pre class="brush: java; title: ; notranslate"> scala&gt; numbers.reduceLeft((x,y) =&gt; if ( x &lt; y ) y else x) res7: Int = 587 </pre>
<p>Lets look at a way to increment each number in the collection and return a new collection instead of editing the original collection:</p>
<pre class="brush: java; title: ; notranslate"> scala&gt; numbers.map(x =&gt; x +10)
res8: List[Int] = List(13, 14, 571, 12, 597, 44, 33)

scala&gt; println(numbers)
List(3, 4, 561, 2, 587, 34, 23)
</pre>
<p>the original collection remains the same.</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.map(_+10)
res11: List[Int] = List(13, 14, 571, 12, 597, 44, 33)
</pre>
<p>we can also omit the parameters for the function value and then replace it with <strong>_</strong></p>
<p>Finding factorial using foldLeft:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; 1.to(5).foldLeft(1)((x,y) =&gt; x * y)
res23: Int = 120
</pre>
<p>the foldLeft is exactly similar to reduceLeft but the only difference is that it takes an initial value and then uses it to apply the function passed.</p>
<h4>Currying</h4>
<p><strong>Currying</strong> transforms a function that takes multiple parameters into a chain of functions each taking a single parameter. We have seen <strong>increaseByFactor</strong> taking 2 parameters- the value to be incremented and the factor by which to increment. The curried version of the same would be:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; def curriedIncrement(factor:Int) = (x:Int) =&gt; factor * x
curriedIncrement: (factor: Int)(Int) =&gt; Int

scala&gt; val incrementBy5 = curriedIncrement(5)
incrementBy5: (Int) =&gt; Int =

scala&gt; println(incrementBy5(10))
50

scala&gt; val incrementBy2 = curriedIncrement(2)
incrementBy2: (Int) =&gt; Int =

scala&gt; println(incrementBy2(10))
20
</pre>
<p>In the above example the curriedIncrement takes in a factor parameter and returns another function with the factor parameter curried into it (something like half cooked function) and then we can create multiple instance of curriedIncrement by passing in different factor values.</p>
<p>We already saw currying being used in the above example when we used foldLeft:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; 1.to(5).foldLeft(1)((x,y) =&gt; x * y)
res23: Int = 120
</pre>
<p>These are some of the basic concepts which would help any Java programmer to get started with the Functional concepts of Scala. If you are interested to learn more then I would highly recommend <a href="//www.flipkart.com/programming-scala-2nd-0981531644/p/itmdyf78mzkjtd5a?pid=9780981531649&amp;affid=suthukrish" target="_blank">Programming in Scala</a> book by Martin Odersky and others.</p>
<blockquote><p><span style="color: #000080"> <strong>One can buy Programming in Scala from <span style="color: #800000"><a href="//www.flipkart.com/programming-scala-2nd-0981531644/p/itmdyf78mzkjtd5a?pid=9780981531649&amp;affid=suthukrish" target="_blank"><span style="color: #800000">Flipkart</span></a></span> or <span style="color: #800000"><a href="http://astore.amazon.com/javabeat-20/detail/0981531644" target="_blank"><span style="color: #800000">Amazon</span></a></span>.</strong></span></p></blockquote>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/functions-as-first-class-citizens-in-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Apply and Unapply Methods in Scala</title>
		<link>http://www.javabeat.net/2012/07/using-apply-unapply-methods-scala/</link>
		<comments>http://www.javabeat.net/2012/07/using-apply-unapply-methods-scala/#comments</comments>
		<pubDate>Sat, 07 Jul 2012 17:16:40 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4627</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Before we proceed to learn about Apply and Unapply methods, its good to know what a companion object is. A companion object in Scala for some class say Fraction is defined as: One can provide apply(args) and unapply(args) methods in the companion objects which can be used implemented to some special operations in Scala. Suppose [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Before we proceed to learn about Apply and Unapply methods, its good to know what a companion object is. A companion object in Scala for some class say Fraction is defined as:</p>
<pre class="brush: java; title: ; notranslate">
class Fraction(var numerator:Int, var denominator:Int){

  def *(fraction2:Fraction) = {

    Fraction(this.numerator*fraction2.numerator,
             this.denominator*fraction2.denominator)
  }

  override def toString = this.numerator+&quot;/&quot;+this.denominator
}

//the below construct is the companion object for Fraction class.
object Fraction{

}

</pre>
<p>One can provide apply(args) and unapply(args) methods in the companion objects which can be used implemented to some special operations in Scala. Suppose for example you wish to create a Fraction instead as below:</p>
<pre class="brush: java; title: ; notranslate">
val fraction1 = Fraction(3,4)
</pre>
<p>the above line behind the scenes invokes the apply method provided in the companion object for Fraction. Similarly suppose I want to extract the contents of an instance and assign them to another object, something like:</p>
<pre class="brush: java; title: ; notranslate">
val fract1 = Fraction(3,4)
val fract2 = Fraction(2,4)
val Fraction(numer, denom) = fract1 * fract2
println(&quot;Numerator: &quot;+numer+&quot; Denominator: &quot;+denom)
</pre>
<p>the above code invokes the unapply() method behind the scenes. </p>
<p>In the apply method we take the required parameters and return the new instance of class we are interested in where as we do the reverse in unapply- we take the instance and extract out the required information and return them in the form of a <a href="http://blog.sanaulla.info/tuples-scala/" target="_blank">tuple</a>. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets add those methods in the Fraction object</p>
<pre class="brush: java; title: ; notranslate">
object Fraction{

  def apply(numer:Int, denom:Int) = new Fraction(numer,denom)

  def unapply(fraction:Fraction) = {
    if ( fraction == null ) None
    else Some(fraction.numerator, fraction.denominator)
  }

}
</pre>
<p>Check <a href="http://www.javabeat.net/2012/06/handlingavoiding-nulls-in-java-using-guava-versus-scala/" title="Handling/Avoiding Null’s in Java using Guava versus Scala" target="_blank">this</a> out if you are curious about Some and None. The idea is simple- in apply method take the parameter required and then return a new Fraction instance and in the unapply extract the values in the fields of the object and then return those values. Lets see these things in action:</p>
<pre class="brush: java; title: ; notranslate">

object Main extends App{

  println(Fraction(3,4) * Fraction(2,4) )

  val Fraction(numer, denom) = Fraction(1,4) * Fraction(4,5)

  println(&quot;Numerator: &quot;+numer+&quot; Denominator: &quot;+denom)
}

</pre>
<p>The output: </p>
<pre class="brush: bash; title: ; notranslate">
6/16
Numerator: 4 Denominator: 20
</pre>
<p>Lets see other examples of how the apply and unapply methods can be used. There&#8217;s another method called: unapplySeq which can be used to extract an arbitrary sequence of values. We can use unapply to extract any data from the given data. This is particularly useful in pattern matching where Case classes as used. Case classes already implement these apply and unapply methods. </p>
<pre class="brush: java; title: ; notranslate">
object Name{
  def unapply(input:String) = {
    val pos = input.indexOf(&quot; &quot;)
    if ( pos == -1 ) None
    else Some(input.substring(0,pos), input.substring(pos+1))
  }
}

object Main extends App{

  val personName = &quot;FirstName LastName&quot;
  val Name(firstName, lastName) = personName
  println(firstName+&quot; Last: &quot;+lastName)

}
</pre>
<p>In the above code we extract the first name and last name from the given name assuming the first and last name are made up of one word respectively. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/using-apply-unapply-methods-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Traits in Scala- Advanced concepts</title>
		<link>http://www.javabeat.net/2012/07/traits-scala-advanced-concepts/</link>
		<comments>http://www.javabeat.net/2012/07/traits-scala-advanced-concepts/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 10:00:22 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[scala traits]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4599</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous article we covered very basic concepts on traits. In this article we will expand on our initial work and explore the inherent power of traits. As we said here just like the Interfaces traits can have abstract methods. Also traits can extend other traits just like Interfaces can extend other interfaces. We [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our <a href="http://www.javabeat.net/2012/07/traits-scala/" title="Traits in Scala">previous article</a> we covered very basic concepts on traits. In this article we will expand on our initial work and explore the inherent power of traits. </p>
<p>As we said <a href="http://www.javabeat.net/2012/07/traits-scala/" title="Traits in Scala">here</a> just like the Interfaces traits can have abstract methods. Also traits can extend other traits just like Interfaces can extend other interfaces. </p>
<pre class="brush: java; title: ; notranslate">
trait Reader{
  def read(source:String):String 
}

trait StringReader extends Reader {
  override def read(source:String) = {
    Source.fromString(source).mkString
  }
}
</pre>
<p>We have seen <a href="http://www.javabeat.net/2012/07/traits-scala/" title="Traits in Scala">previously</a> about adding trait to the class declaration, but that&#8217;s not the only way to add a trait. One can mix in a trait during the object creation as well. But before that lets modify the Reader trait to make the method read to return some default string.</p>
<pre class="brush: java; title: ; notranslate">
</pre>
<p>Now lets look at an example to mixin a trait while creating object:</p>
<pre class="brush: java; title: ; notranslate">
class Person(var name:String, var age:Int){
  def getDetails = name+ &quot; &quot;+ age
}

class Student(name:String, age:Int, var moreDetails:String)
    extends Person(name,age) with Reader{

  override def getDetails = {

    val details = read(moreDetails)
    &quot;Student details\n&quot;+name+
    &quot; &quot;+age+&quot;\n&quot;+&quot;More: &quot;+details

  }

}
</pre>
<p>Lets create an instance of above Student class without including the StringReader trait.</p>
<pre class="brush: java; title: ; notranslate">

object Main extends App{

  val student1 = new Student(&quot;Sana&quot;, 20,
                       &quot;About the student&quot;)

  println(student1.getDetails)
}

</pre>
<p>The output would be:</p>
<pre class="brush: java; title: ; notranslate">
Student details
Sana 20
More: DEFAULT
</pre>
<p>Really not useful, the Reader trait is not enough, so we make use of adding a trait during object creation:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends App{

  val student1 = new Student(&quot;Sana&quot;, 20,
          &quot;About the student&quot;) with StringReader

  println(student1.getDetails)
}
</pre>
<p>The output:</p>
<pre class="brush: bash; title: ; notranslate">
Student details
Sana 20
More: About the student
</pre>
<p>Now we have more meaningful information and not the default implementation. Traits can also have fields- fields can be concrete and abstract. If an initial value is provided for the field in the trait then it becomes a concrete field, otherwise it is an abstract field, something like:</p>
<pre class="brush: java; title: ; notranslate">
import scala.io.Source
trait Reader{
  var source = &quot;DEFAULT&quot;
  def read = source
}

trait StringReader extends Reader {

  override def read = {
    Source.fromString(source).mkString
  }

}

class Person(var name:String, var age:Int){
  def getDetails = name+ &quot; &quot;+ age
}

class Student(name:String, age:Int, moreDetails:String)
    extends Person(name,age) with Reader{

  source = moreDetails

  override def getDetails = {
    val details = read
    &quot;Student details\n&quot;+name+&quot; &quot;+age+&quot;\n&quot;+&quot;More: &quot;+details
  }
}

object Main extends App{

  val student1 = new Student(&quot;Sana&quot;, 20,
          &quot;About the student&quot;) with StringReader

  println(student1.getDetails)
}
</pre>
<p>We just edited the trait and moved the parameter for read method into the field for the trait. And in the class Student we assign a new value to the <strong>source</strong> field in the trait. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h4>Layering Traits</h4>
<p>One can chain the traits such that one trait can invoke another version of the same method in a different trait. Lets add 2 more traits- FileReader and UrlReader. FileReader would read from a file and UrlReader would read content from a given URL. </p>
<pre class="brush: java; title: ; notranslate">
trait FileReader extends Reader{

  override def read(source:String) = {
    Source.fromFile(source,&quot;UTF-8&quot;).mkString
  }
}

trait UrlReader extends Reader{

  override def read(source:String) = {
    Source.fromURL(super.read(source),&quot;UTF-8&quot;).mkString
  }
}
</pre>
<p>Interesting to see super.read(source) in the UrlReader trait. Does that mean it inokves the read(source) in Reader trait? We wouldn&#8217;t expect anything useful from the read(source) version of Reader method. Instead, super.read(source) calls the next trait in the trait hierarchy, which depends on the order in which the traits are added. The traits are processed starting with the last one. Lets see how this makes sense:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends App{

  //case 1
  val student2 = new Student(&quot;Stud1&quot;,20, &quot;/tmp/url&quot;)
          with FileReader with UrlReader

  println(student2.getDetails)

  //case 2
  val student3 = new Student(&quot;Stud2&quot;,20,&quot;http://javabeat.net&quot;)
          with StringReader with UrlReader

  println(student3.getDetails)
}
</pre>
<p>In the case 1 we add FileReader and UrlReader traits. When UrlReader invokes super.read(source), the read(source) from the FileReader is invoked and you would expect to have a URL in the /tmp/url file.<br />
In the case 2 we add StringReader and UrlReader traits. When the UrlReader invokes super.read(source), the read(source) from the StringReader is invoked. </p>
<p>The example above seems pretty naive and can be implemented in a more concise way. I havent been able to come up with a better example. But I hope I have been able to convey the concept though. </p>
<p>Another interesting concept to explore is how the traits are mapped to the classes which the JVM can consume.<br />
A trait with abstract method:</p>
<pre class="brush: java; title: ; notranslate">
trait Reader{
  def read(source:String):String
}
</pre>
<p>translates to a usual Interface in Java</p>
<pre class="brush: java; title: ; notranslate">
Compiled from &quot;TraitTrans.scala&quot;
public interface Reader {
  public abstract java.lang.String read(java.lang.String);
}
</pre>
<p>A trait with method definition would translate into a Interface and a abstract class which has the implementations in the trait moved into static methods. Something like</p>
<pre class="brush: java; title: ; notranslate">
trait Reader{
  def read(source:String):String
}

trait StringReader extends Reader{
  import scala.io.Source
  def read(source:String) = 
    Source.fromString(source).mkString
}
</pre>
<p>would create StringReader.class and StringReader$class.class files where in the StringReader.class is the interface and StringReader$class.class is an abstract class with the implementations in the static methods</p>
<pre class="brush: java; title: ; notranslate">
mohamed@mohamed-Aspire-4710:~/scalaP$ javap -c StringReader.class 
Compiled from &quot;TraitTrans.scala&quot;
public abstract class StringReader$class {
  public static java.lang.String read(StringReader, java.lang.String);
    Code:
       0: getstatic     #11                 // Field scala/io/Source$.MODULE$:Lscala/io/Source$;
       3: aload_1       
       4: invokevirtual #16                 // Method scala/io/Source$.fromString:(Ljava/lang/String;)Lscala/io/Source;
       7: invokeinterface #22,  1           // InterfaceMethod scala/collection/TraversableOnce.mkString:()Ljava/lang/String;
      12: areturn       

  public static void $init$(StringReader);
    Code:
       0: return        
}
</pre>
<p>One can make out that the companion class generated contains the method implementations. <a href="http://stackoverflow.com/questions/7637752/using-scala-traits-with-implemented-methods-in-java/7637888#7637888" target="_blank">Here</a> is a superb description of how the traits and classes extending traits get translated to the classfiles for the JVM. </p>
<p>These are few concepts which are worth learning as part of Traits. Another important concept is the Trait construction order and Self Types which I might cover in future posts. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/traits-scala-advanced-concepts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Traits in Scala</title>
		<link>http://www.javabeat.net/2012/07/traits-scala/</link>
		<comments>http://www.javabeat.net/2012/07/traits-scala/#comments</comments>
		<pubDate>Thu, 05 Jul 2012 18:05:39 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4596</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Java doesn&#8217;t allow multiple inheritance for the fear of Deadly Diamond of Death. And to circumvent this Java introduced interfaces where in a class can extend only one other class, but implement multiple interfaces. These interfaces don&#8217;t contain any implementations. (This is going to change with Defender Methods in Java 8). Lot of other languages [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Java doesn&#8217;t allow multiple inheritance for the fear of <a href="http://en.wikipedia.org/wiki/Diamond_problem" target="_blank">Deadly Diamond of Death</a>. And to circumvent this Java introduced interfaces where in a class can extend only one other class, but implement multiple interfaces. These interfaces don&#8217;t contain any implementations. (This is going to change with <a href="http://www.javabeat.net/2012/05/virtual-extension-methods-in-java-8/" title="Virtual Extension Methods(or Defender Methods) in Java 8" target="_blank">Defender Methods</a> in Java 8). Lot of other languages support interface like constructs but with greater power. And one such construct in Scala are Traits. </p>
<h4>Traits like Interfaces in Java</h4>
<p>Lets have a look at Trait being used as a Interface in Java. Consider a Trait Reader which provides a abstract read method.</p>
<pre class="brush: java; title: ; notranslate">
trait Reader{
  def read(source:String):String
}
</pre>
<p>This trait can be extended by Scala classes like:</p>
<pre class="brush: java; title: ; notranslate">
class StringReader extends Reader{
  import scala.io.Source
  def read(source:String) = 
      Source.fromString(source).mkString
}
</pre>
<p>In Scala we can place imports at any line. Lets see the above code in action:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends App{
  val stringReader = new StringReader
  println(stringReader
        .read(&quot;This is a string to be printed back&quot;))
  println(stringReader.isInstanceOf[Reader])
}
</pre>
<p>The output is:</p>
<pre class="brush: bash; title: ; notranslate">
This is a string to be printed back
true
</pre>
<p>You must be thinking: But this is what an Interface can do, how is a trait different? </p>
<h4>Traits with method implementations</h4>
<p>Let me edit the Reader trait to implement read method to read the contents from the String i.e what StringReader does. </p>
<pre class="brush: java; title: ; notranslate">
trait Reader{
  def read(source:String):String =
    Source.fromString(source).mkString
}
</pre>
<p>Here is the power of traits. They can have implementations. A real advantage is that lot of times we have common implementations of certain methods in Interfaces and we end up implementing those interfaces and copying the code at all the places- A clear violation of <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank">DRY</a>. Java is introducing a similar concept in Java 8 called <a href="http://www.javabeat.net/2012/05/virtual-extension-methods-in-java-8/" title="Virtual Extension Methods(or Defender Methods) in Java 8" target="_blank">Defender Methods</a>. The main intention of introducing Defender Methods is for enhancing the APIs in such a way that it doesnt break millions of existing implementations. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets <strong>mix in</strong> the above trait into a class.</p>
<pre class="brush: java; title: ; notranslate">
class Person(var name:String, var age:Int){
  def getDetails = name+ &quot; &quot;+ age
}

class Employee(name:String, age:Int, var moreDetails:String)
    extends Person(name,age) with Reader{

  override def getDetails = {
    val details = read(moreDetails)
    name + &quot; &quot;+age+&quot;\n&quot;+&quot;More: &quot;+details
  }

}
</pre>
<p>We have a Employee class which extends Person class and mixes in the Reader trait. Just like in Java we use <strong>implements</strong> keyword, in Scala we use <strong>with</strong> keyword for adding a trait. When we mix in the trait, all its contents are just added as is into the class, which means the <strong>read</strong> method in the Reader trait can be invoked from the Employee class just as if the method was actually a part of Employee class. </p>
<p>Lets see the above classes in Action:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends App{

  val employee1 = new Employee(&quot;Alex&quot;,20,
                       &quot;Some more details as string&quot;)

  println(employee1.getDetails)
}
</pre>
<p>The output:</p>
<pre class="brush: bash; title: ; notranslate">
Alex 20
More: Some more details as string
</pre>
<p>These were some of the basic concepts of Traits. There&#8217;s lot of things yet to be explored, I think I will cover the advanced concepts in a subsequent article. </p>
<p>The complete code for the above example:</p>
<pre class="brush: java; title: ; notranslate">
import scala.io.Source

trait Reader{
  def read(source:String):String =
    Source.fromString(source).mkString
}
class Person(var name:String, var age:Int){
  def getDetails = name+ &quot; &quot;+ age
}

class Employee(name:String, age:Int, var moreDetails:String)
    extends Person(name,age) with Reader{

  override def getDetails = {
    val details = read(moreDetails)
    name + &quot; &quot;+age+&quot;\n&quot;+&quot;More: &quot;+details
  }

}

object Main extends App{

  val employee1 = new Employee(&quot;Alex&quot;,20,
                       &quot;Some more details as string&quot;)

  println(employee1.getDetails)
}
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/traits-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Inheritance and Overriding in Scala</title>
		<link>http://www.javabeat.net/2012/07/inheritance-overriding-scala/</link>
		<comments>http://www.javabeat.net/2012/07/inheritance-overriding-scala/#comments</comments>
		<pubDate>Wed, 04 Jul 2012 19:01:15 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4590</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Inheritance in Scala is quite similar to the way it is in Java. The overriding aspects are a bit more detailed because in Scala there are not just methods to override but also vals, vars. There are a few restrictions added in Scala like: Overriding classes must use the &#8220;override&#8221; modifier. In Java one can [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Inheritance in Scala is quite similar to the way it is in Java. The overriding aspects are a bit more detailed because in Scala there are not just methods to override but also vals, vars. There are a few restrictions added in Scala like:</p>
<ul>
<li>Overriding classes must use the &#8220;override&#8221; modifier. In Java one can use the @Override annotation to enforce correct overriding</li>
<li>Auxiliary constructors cannot directly invoke the super class constructors. They only can invoke the primary constructor which in turn would invoke the Super class constructor. Read <a href="http://www.javabeat.net/2012/06/primary-auxiliary-constructors-scala/" title="Primary and Auxiliary Constructors in Scala" target="_blank">here</a> to know more about Primary and Auxiliary constructors in Scala</li>
</ul>
<p>In this article we will have a look at Inheritance concepts in Scala along with the restrictions related to overriding members of the class. First lets look at plain Inheritance. </p>
<h4>Inheritance in Scala</h4>
<p>Just like in Java, classes in Scala can extend other classes using the <strong>extends</strong> keyword. And Scala also doesn&#8217;t support Multiple Inheritance, but just like in Java we have Interfaces, in Scala we have Traits. We would learn about Traits in future posts. But for now they are kind-of equivalent to Interfaces in Java (not completely similar to Interfaces). </p>
<p>Suppose we have a Item class which has two fields- price and description:</p>
<pre class="brush: java; title: ; notranslate">
class Item(var price:Double, var description:String){
  override def toString():String = {
    description+&quot; Cost: &quot;+price
  }
}
</pre>
<p>Every class in Scala are subclasses of <a href="http://www.scala-lang.org/api/current/index.html#scala.AnyRef" target="_blank">AnyRef</a>, just like we have Object in Java. But values like Int, Double, Byte, Char, Float, Short, Boolean, Unit (void) and similar others are subclasses of <a href="http://www.scala-lang.org/api/current/index.html#scala.AnyVal" target="_blank">AnyVal</a>. The toString() method is defined in AnyRef class and hence we use the <strong>override</strong> modifier when we override that method. </p>
<p>Lets have a SpecialItem class which extends Item.</p>
<pre class="brush: java; title: ; notranslate">
class SpecialItem(price:Double, description:String)
        extends Item(price,description){
}
</pre>
<p>As I said before the constructor of the super class can be invoked only from the Primary Constructor of the sub class. From <a href="http://www.javabeat.net/2012/06/primary-auxiliary-constructors-scala/" title="Primary and Auxiliary Constructors in Scala" target="_blank">here</a> we know that the Primary Constructor spans complete class declaration. So there is no best place to invoke the superclass constructor than in along with the extends clause. </p>
<p>Lets create an instance of both these types and print their contents:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">

object Main extends App{
  val item = new Item(45.6,&quot;Book&quot;)
  println(item)
  //Book Cost: 45.6
  val specialItem = new SpecialItem(56.8,&quot;Sepcial Book&quot;)
  println(specialItem)
  //Sepcial Book Cost: 56.8
}
</pre>
<p>Now that we have seen how classes can be extended in Scala, lets have a look at the restrictions related to overriding.</p>
<h4>Overriding def&#8217;s</h4>
<p>In Scala methods are declared by using &#8220;def&#8221; keyword. Suppose we need to calculate discounted price which can vary across items. For a simple Item there is no discounted price, but for a SpecialItem there would be a discount percentage value that would be taken and discounted price calculated based on that. Lets see how we can modify the above classes to add this functionality.</p>
<pre class="brush: java; title: ; notranslate">
class Item(var price:Double, var description:String){
  //No discount for Item
  def discountedPrice():Double = price

  override def toString():String = {
    description+&quot; Cost: &quot;+discountedPrice()
  }
}
class SpecialItem(price:Double, 
                  description:String, 
                  var discountPercent:Double)
        extends Item(price,description){
  //Discounted price
  override def discountedPrice():Double = {
    price - ((discountPercent/100) * price)
  }
}
</pre>
<p>In the constructor of SpecialItem we take an extra parameter for discount percentage. We declare it as var so discount percentage becomes a filed in the SpecialItem class and there would be getters/setters generated for discount percentage. Lets pass the discount percentage while constructing the SpecialItem instance:</p>
<pre class="brush: java; title: ; notranslate">
object Main extends App{
  val item = new Item(45.6,&quot;Book&quot;)
  println(item)
  //Book Cost: 45.6
  val specialItem = new SpecialItem(56.8,&quot;Sepcial Book&quot;, 10)
  println(specialItem)
  //Sepcial Book Cost: 51.12
}
</pre>
<p>Some restrictions related to Overriding:<br />
- Cannot override a var with a val or def, doing this is an error:</p>
<pre class="brush: java; title: ; notranslate">
class Item(var price:Double, var description:String){
  var discountedPrice = price

  override def toString():String = {
    description+&quot; Cost: &quot;+discountedPrice
  }
}

class SpecialItem(price:Double, 
                  description:String, 
                  var discountPercent:Double)
        extends Item(price,description){
  //This is an error for both def and val
  override def discountedPrice:Double = {
    price - ((discountPercent/100) * price)
  }
}
</pre>
<p>In case there the <strong>var</strong> in super class is abstract then it can be overridden in the subclass.<br />
- A val in Superclass cannot be overridden by var or def in subclass. </p>
<h4>Overriding def with var</h4>
<p>A field declared as var can override the def defined in the Superclass. The important thing to note here is that a var can override only a getter/setter pair in the Super class. Let me explain you with an example:</p>
<pre class="brush: java; title: ; notranslate">
class Item(var price:Double, var description:String){
  def discountedPrice_=(discPrice:Double){ price = discPrice}
  def discountedPrice = price

  override def toString():String = {
    description+&quot; Cost: &quot;+discountedPrice
  }
}

class SpecialItem(price:Double, 
                  description:String, 
                  override var discountedPrice:Double)
        extends Item(price,description){
}
</pre>
<p>In the above example the Item class has a getter/setter like methods and in the SpecialItem we make use of discountedPrice field which is declared as var to override the discountedPrice getter/setter pair in the Super class. Suppose we remove the override modifier from the discountedPrice field, we would get the following error:</p>
<pre class="brush: bash; title: ; notranslate">
InheritanceTest.scala:10: error: overriding method 
discountedPrice in class Item of type =&gt; Double;

 variable discountedPrice needs `override' modifier

class SpecialItem(price:Double, 
                  description:String, 
                  var discountedPrice:Double) 
                                                        ^
one error found
</pre>
<p>These were the few basic concepts related to Inheritance and overriding. We are yet to see how one can declare Abstract classes and also an Interface equivalent in Scala called Traits. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/inheritance-overriding-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Primary and Auxiliary Constructors in Scala</title>
		<link>http://www.javabeat.net/2012/06/primary-auxiliary-constructors-scala/</link>
		<comments>http://www.javabeat.net/2012/06/primary-auxiliary-constructors-scala/#comments</comments>
		<pubDate>Fri, 29 Jun 2012 10:00:37 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4508</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Constructors in Scala are a bit different than in Java. Scala has 2 types of constructors: Primary Constructor Auxiliary Constructor Primary Constructor In Java we have a no-args default constructor which is provided for every class which doesn&#8217;t provide its own constructor methods. On a similar lines Primary Constructor in Scala is the kind-of default [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Constructors in Scala are a bit different than in Java. Scala has 2 types of constructors:</p>
<ul>
<li>Primary Constructor</li>
<li>Auxiliary Constructor</li>
</ul>
<h4>Primary Constructor</h4>
<p>In Java we have a no-args default constructor which is provided for every class which doesn&#8217;t provide its own constructor methods. On a similar lines Primary Constructor in Scala is the kind-of default constructor in the way every class in Scala would have a Primary Constructor.</p>
<p>The primary constructor spans the complete class definition i.e in the example below the age field gets initialized as part of the Primary Constructor of the Employee class.</p>
<pre class="brush: java; title: ; notranslate">
class Employee{
  var age:Int = 20
}
</pre>
<p>In the above example the primary constructor didn&#8217;t accept any parameters. But the primary constructor can also accepts parameters, this is where it is different from default constructors in Java. Let me not try to draw an analogy any further.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
class Employee(val firstName:String,
               val lastName:String){

  override def toString():String = {

    &quot;First Name: &quot;+firstName+&quot; Last Name: &quot;+lastName
  }
}
</pre>
<h4>Auxiliary Constructor</h4>
<p>In Java one can overload the constructors to provide different constructors accepting different parameters. On similar lines Scala classes can declare Auxiliary constructors which are overloaded forms of the Primary Constructor. The auxiliary constructors are named as <strong>this</strong>. Lets see an example:</p>
<pre class="brush: java; title: ; notranslate">
class Employee(val firstName:String, val lastName:String){
  var age:Int = 0

  //Auxiliary Constructor
  def this(firstName:String, lastName: String, age:Int){

    this(firstName,lastName)
    this.age = age

  }

  override def toString():String = {
    &quot;First Name: &quot;+firstName+&quot; Last Name: &quot;+lastName
  }

}
</pre>
<p>There&#8217;s a catch here- The auxiliary constructor can invoke the primary constructor or an auxiliary constructor declared just before it, which means the below code will not work:</p>
<pre class="brush: java; title: ; notranslate">
class Employee(val firstName:String, val lastName:String){
  var age:Int = 0
  var city:String = _

  def this(firstName:String, lastName: String,
           city:String, age:Int){
    this(firstName, lastName, city)
    this.age = age

  }
  def this(firstName:String, lastName: String, city:String){
    this(firstName,lastName)
    this.city = city

  }

  override def toString():String = {
    &quot;First Name: &quot;+firstName+&quot; Last Name: &quot;+lastName
  }

}
</pre>
<p>Trying to compile the above code results in:</p>
<pre class="brush: bash; title: ; notranslate">
$ scalac Employee.scala
Employee.scala:9:error: called constructor's definition must
precede calling constructor's definition
    this(firstName, lastName, city)
    ^
one error found
</pre>
<p>the error clearly says what&#8217;s wrong. One would have to take care of this, though the compiler would report such issues, but its always good to know.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/primary-auxiliary-constructors-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Package Objects in Scala</title>
		<link>http://www.javabeat.net/2012/06/package-objects-scala/</link>
		<comments>http://www.javabeat.net/2012/06/package-objects-scala/#comments</comments>
		<pubDate>Thu, 28 Jun 2012 14:58:30 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4494</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Package Objects in Scala was introduced as part of Scala 2.8. With this feature a package in scala can contain field declarations, methods along with the classes, objects and traits. The methods and variable declarations are put into the package object and are accessible in the package for which the package object was declared. Lets [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Package Objects in Scala was introduced as part of Scala 2.8. With this feature a package in scala can contain field declarations, methods along with the classes, objects and traits. The methods and variable declarations are put into the package object and are accessible in the package for which the package object was declared.</p>
<p>Lets take a look at very simple example.</p>
<pre class="brush: java; title: ; notranslate">
//File: TestClass.scala
package net{

  package javabeat{

    class TestClass{

      def instanceMethod():String = {
        println(&quot;From TestClass: &quot;+packageMethod1)
        &quot;Invoked instance method&quot;
      }

    }

    object TestClass extends App{

      val testObj = new TestClass
      println(testObj.instanceMethod)

      println(packageMethod1)

      println(packageField1)
    }
  }
}

package net{

  package object javabeat{

    def packageMethod1():String = {
      &quot;Invoked Package Method1&quot;
    }

    val packageField1 = &quot;Package Field1&quot;
  }
}
</pre>
<p>Unlike Java, in Scala the packages can be nested, something like show in the above example. The package declaration in the above example can also be written as net.javabeat. And Scala doesn&#8217;t enforce the classes declared in a package should be placed in the same directory structure. One could have all the classes in the same folder but when you compile the source, it creates the class files in the directory structure as per the package name.</p>
<p>In the above example we declared a package object using the syntax <strong>package object</strong>. We declared a method <strong>packageMethod1</strong> and a field <strong>packageField1</strong> in the <strong>package object javabeat</strong>. In the class TestClass defined in the package net.javabeat we try to access the method defined in the package object.</p>
<p>Someone very new to Scala would wonder about the following code:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
object TestClass extends App{

  val testObj = new TestClass
  println(testObj.instanceMethod)

  println(packageMethod1)

  println(packageField1)
}
</pre>
<p>The above code creates a companion object for the class TestClass. The companion object is nothing but a singleton instance for the class for which it is a companion object. And the companion object can extend other classes, and also mixin traits. We extended the App object which wraps the code within the object declaration into a main method.</p>
<p>In short the methods, fields declared in the package object are accessible throughout the package. Lets compile and run the above code:</p>
<pre class="brush: bash; title: ; notranslate">
$ scalac TestClass.scala
$ scala net.javabeat.TestClass
From TestClass: Invoked Package Method1
Invoked instance method
Invoked Package Method1
Package Field1
</pre>
<p>If you get the following error:</p>
<pre class="brush: bash; title: ; notranslate">
TestClass.scala:15: error: not found: type App
    object TestClass extends App{
                             ^
one error found
</pre>
<p>then you need to use the latest Scala version or you can replace extends App with extends Application.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/package-objects-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fields which satisfy JavaBean specification &#8211; BeanProperties in Scala</title>
		<link>http://www.javabeat.net/2012/06/fields-which-satisfy-javabean-specification-beanproperites-in-scala/</link>
		<comments>http://www.javabeat.net/2012/06/fields-which-satisfy-javabean-specification-beanproperites-in-scala/#comments</comments>
		<pubDate>Tue, 26 Jun 2012 15:11:18 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4475</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We have seen previously about declaring fields in classes in Scala and also saw the kind of bytecode created for each of the cases. But lot of Java tools out there expect the fields in classes to follow the JavaBeans specification and in order to support that Scala provides @BeanProperty annotation. BeanProperties in Scala Lets [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We have seen <a href="http://www.javabeat.net/2012/06/understanding-classes-fields-scala/" target="_blank">previously</a> about declaring fields in classes in Scala and also saw the kind of bytecode created for each of the cases. But lot of Java tools out there expect the fields in classes to follow the JavaBeans specification and in order to support that Scala provides @BeanProperty annotation.</p>
<h3>BeanProperties in Scala</h3>
<p>Lets have a look at some code:</p>
<pre class="brush: java; title: ; notranslate">
import scala.reflect.BeanProperty
class Book{
  @BeanProperty var title:String = _
  @BeanProperty val isbn:String = &quot;ISBN10&quot;
}
</pre>
<p>Lets compile the above code and use <strong>javap</strong> to inspect the bytecode.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: bash; title: ; notranslate">
$ scalac Book.scala
$ javap Book.class
Compiled from &quot;Book.scala&quot;
public class Book implements scala.ScalaObject {
  public java.lang.String title();
  public void title_$eq(java.lang.String);
  public void setTitle(java.lang.String);
  public java.lang.String isbn();
  public java.lang.String getIsbn();
  public java.lang.String getTitle();
  public Book();
}
</pre>
<p>The field which was declared with <strong>var</strong> keyword would have a getField and setField generated where as the field declared with <strong>val</strong> keyword would have only a getField generated. We already know from <a href="http://blog.sanaulla.info/2009/07/02/val-versus-var-in-scala/" target="_blank">here</a> the difference between val and var.</p>
<p>In the above example, <strong>title</strong> is declared as <strong>var</strong> and <strong>isbn</strong> is declared as <strong>val</strong>. Hence there are getters and setters assocaited with <strong>title</strong> field and only getter associated with the <strong>isbn</strong> field</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/fields-which-satisfy-javabean-specification-beanproperites-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
