JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Playing with reduceLeft, reduceRight, foldLeft, foldRight API in Scala

July 18, 2012 by Mohamed Sanaulla Leave a Comment

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 easier to study them together.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

reduceLeft/reduceRight: The scala doc declares this method as:
[code lang=”java”] reduceLeft[B >: A](op: (B, A) ⇒ B): B[/code]
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.
Lets use this reduceLeft to find out the largest and smallest elements in the collection of numbers:
[code lang=”java”]
scala> numbers.reduceLeft((x,a) => if ( x < a ) a else x)
res86: Int = 42
//smallest element
scala> numbers.reduceLeft((x,a) => if ( x < a) x else a)
res87: Int = 2
[/code]

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.
[code lang=”java”]
scala> val numbers = List(4,21,2,4,62,345,67)
numbers: List[Int] = List(4, 21, 2, 4, 62, 345, 67)

//finding maximum
scala> numbers.reduceRight((x,v) => if (x > v) x else v)
res0: Int = 345

//finding minimum
scala> numbers.reduceRight((x,v) => if (x < v) x else v)
res1: Int = 2
[/code]

foldLeft/foldRight: 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.
Suppose we want to find the sum of the elements in a list (I can use the “sum” method directly, but for understanding I would use foldLeft/reduceLeft):
[code lang=”java”]
scala> 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> numbers.foldLeft(0)((sum,x) => sum + x)
res0: Int = 55

//initial seed value of 10 added 10 to the final sum.
scala> numbers.foldLeft(10)((sum,x) => sum + x)
res1: Int = 65
[/code]
One another use of foldLeft is to find the factorial:
[code lang=”java”]
//factorial of 5
scala> 1.to(5).foldLeft(1)((prod,x)=>prod*x)
res3: Int = 120

//factorial of 6
scala> 1.to(6).foldLeft(1)((prod,x)=>prod*x)
res4: Int = 720
[/code]

scanLeft/scanRight: 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.
Lets look at the same factorial example using scanLeft/scanRight:
[code lang=”java”]
scala> 1.to(6).scanLeft(1)((prod,x)=>prod*x)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 1, 2, 6, 24, 120, 720)

scala> 1.to(6).scanRight(1)((prod,x)=>prod*x)
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 6, 30, 120, 360, 720, 720)
[/code]

Filed Under: Scala Tagged With: scala

Playing with Collections API in Scala

July 16, 2012 by Mohamed Sanaulla Leave a Comment

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 List for all the methods.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

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.

map, foreach, flatMap, collect:

defining a List:
[code lang=”java”]
scala> 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)
[/code]
All the collection classes in Scala extend the Iterable trait and right through this post we will keep that API doc page open as we would repeatedly refer to it.

foreach: This methods iterates over the elements in the collection and applies the function passed to the foreach method. There’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) => {block} (we can make this more concise, I will show in the example)
[code lang=”java”]
scala> numbers.foreach((x) => {print(x+" ")})
2 3 4 5 6 7 23 42 34
scala> numbers.foreach(x => print(x+" "))
2 3 4 5 6 7 23 42 34
[/code]
You use this when you want to iterate over the collection and perform some operation on the elements.

map: 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:
[code lang=”java”]

scala> numbers.map((x)=> x+2)
res69: List[Int] = List(4, 5, 6, 7, 8, 9, 25, 44, 36)

scala> numbers
res70: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

[/code]
In the Scala Doc the map method is declared as:
[code lang=”java”]
map[B](f: (A) ⇒ B): Iterable[B]
[/code]
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:
[code lang=”java”]
scala> 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)
[/code]
“_” 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’t get modified.

flatMap: There’s a slight twist in this method. The Scala doc declares this method as: flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Iterable[B]. 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 GenTraversableOnce 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:
[code lang=”java”]
//Acts like a map
scala> numbers.flatMap(x => List(x+2))
res73: List[Int] = List(4, 5, 6, 7, 8, 9, 25, 44, 36)

scala> numbers
res74: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala> numbers.flatMap(x => 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)

[/code]
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 “numbers” list. We can return a List instance from the function passed to the map method, but the map method doesn’t flatten the return values to form one collection, the below example would clear this:
[code lang=”java”]
scala> numbers.map(x => 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))
[/code]
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.

collect: This took some time for me to understand. One has to know about Partial Functions before diving into understanding this method. Partial Functions are different from the partially applied functions. 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.
[code lang=”java”]
scala> val partial1:PartialFunction[Int,Int] = { case 1 => 12}
partial1: PartialFunction[Int,Int] = <function1>

scala> partial1.isDefinedAt(1)
res76: Boolean = true

scala> partial1.isDefinedAt(2)
res77: Boolean = false
[/code]
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 here.

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.
[code lang=”java”]
scala> val oneTwoThree:PartialFunction[Int,String] = {case x if x == 1 => "One"
| case x if x == 2 => "Two"
| case x if x == 3 => "Three"
| }
oneTwoThree: PartialFunction[Int,String] = <function1>

scala> numbers
res78: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala> numbers.collect(oneTwoThree)
res79: List[String] = List(Two, Three)
[/code]
One can see that on applying the partial function using the collect method the resultant is a List[String].
Lets look at another example to just get the even numbers from the list:
[code lang=”java”]
scala> numbers
res80: List[Int] = List(2, 3, 4, 5, 6, 7, 23, 42, 34)

scala> val isEven:PartialFunction[Int,Int] = { case x if x % 2 == 0 => x}
isEven: PartialFunction[Int,Int] = <function1>

scala> numbers.collect(isEven)
res81: List[Int] = List(2, 4, 6, 42, 34)
[/code]
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’t satisfy the condition. For example, let me just use map method to implement the above:
[code lang=”java”]
scala> numbers.map((x)=> if ( x % 2 == 0) x)
res82: List[AnyVal] = List(2, (), 4, (), 6, (), (), 42, 34)

[/code]
one can see that in cases where the elements of the collection didn’t satisfy the condition there was an empty value returned.

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.

Filed Under: Scala Tagged With: scala

Functions as First Class Citizens in Scala

July 11, 2012 by Mohamed Sanaulla Leave a Comment

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).

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

In this small article I will show you how to:

  1. Assign functions to variables also called Function Values
  2. Pass functions as arguments to other functions. The functions which accept other functions as parameters are called Higher Order Functions.
  3. Parameter Inference while using Higher Order functions
  4. Currying- which in short is a function which returns another function
  5. Some common higher order functions in Scala collections API

Function Values

Lets see how we can assign a function definition to variable:

[code lang=”java”]
scala> val doubleNumber = (x:Int) => x * 2
doubleNumber: (Int) => Int =
[/code]

The above code was executed in the REPL shell (Read Evaluate Print Loop) which can be accessed by running the command: scala. We can see that the variable doubleNumber is assigned a function which takes an Int and returns another Int. Anything to the left of => are arguments to the function block and anything to the right of => 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:

[code lang=”java”]
scala> println(doubleNumber(7))
14
[/code]

We can also make use of the variables declared outside of the function block, in which case the function value becomes a closure. 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 Java 8.

[code lang=”java”]
scala> val increaseByAFactor = (x: Int) => x * factor
:5: error: not found: value factor
val increaseByAFactor = (x: Int) => x * factor
^
[/code]

the error above is because the function value refers to factor which is not declared before.

[code lang=”java”]
scala> var factor = 3
factor: Int = 3

scala> val increaseByAFactor = (x: Int) => x * factor
increaseByAFactor: (Int) => Int =
[/code]

now invoking the function value we have:

[code lang=”java”]
scala> println(increaseByAFactor(4))
12
[/code]

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.

[code lang=”java”]
scala> val increaseByFactor = (x:Int, factor:Int) => x * factor
increaseByFactor: (Int, Int) => Int =

scala> println(increaseByFactor(4,2))
8
[/code]

Another term associated with Function Value is Function Literal. The function: (x:Int, factor:Int) => x * factor is called as function literal and when assigned to a variable these are together called function values.

Lets dig into how scala compiler handles these function values. For that we would have to compile the above code into bytecode:

[code lang=”java”]
object Main extends Application{
val doubleNumber = (x:Int, factor:Int) => 2 * factor

println(doubleNumber(2,3))
}
[/code]

Once compiled we would have: Main$$anonfun$1.class, Main$.class, Main.class. Inspecting Main.class one of the entries there is:

[code lang=”java”]
public static final scala.Function2 doubleNumber();
[/code]

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.

Higher Order Functions

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 Higher Order Function because it takes in other function as a parameter or can return another function as a return value.

[code lang=”java”]
scala> def performOnRange(low:Int, high:Int, func:Int=>Int){
| low.to(high).foreach(x=> println(func(x)))
| }
performOnRange: (low: Int,high: Int,func: (Int) => Int)Unit
[/code]

Here performOnRange is a higher order function. We can define a function value which would be passed to performOnRange:

[code lang=”java”]
scala> var factor = 5
factor: Int = 5

scala> val incrByFact = (x:Int) => x*factor
incrByFact: (Int) => Int =
[/code]

and then invoke the performOnRange as below:

[code lang=”java”]
scala> performOnRange(1,5,incrByFact)
5
10
15
20
25
[/code]

We could have directly passed the function literal to the performOnRange, something like:

[code lang=”java”]
scala> performOnRange(1,5, (x:Int) => x * factor)
5
10
15
20
25
[/code]

which can be further shortened to:

[code lang=”java”]
scala> performOnRange(1,5, _ * factor)
5
10
15
20
25
[/code]

where each _ stands for a different parameter. In this case we had only on parameter to the function literal and hence only one _.

Common Higher Order Functions in Scala collections

Scala collections API supports the use of higher order functions for operating on the collection data and what’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 Java 8 collections API.

Lets look at few examples:
Finding out the highest number from the array of numbers:

[code lang=”java”]
scala> var numbers = List(3,4,561,2,587,34,23)
numbers: List[Int] = List(3, 4, 561, 2, 587, 34, 23)

scala> numbers.reduceLeft((x:Int,y:Int) => if ( x < y ) y else x) res6: Int = 587 [/code]

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:

[code lang=”java”] scala> numbers.reduceLeft((x,y) => if ( x < y ) y else x) res7: Int = 587 [/code]

Lets look at a way to increment each number in the collection and return a new collection instead of editing the original collection:

[code lang=”java”] scala> numbers.map(x => x +10)
res8: List[Int] = List(13, 14, 571, 12, 597, 44, 33)

scala> println(numbers)
List(3, 4, 561, 2, 587, 34, 23)
[/code]

the original collection remains the same.

[code lang=”java”]
scala> numbers.map(_+10)
res11: List[Int] = List(13, 14, 571, 12, 597, 44, 33)
[/code]

we can also omit the parameters for the function value and then replace it with _

Finding factorial using foldLeft:

[code lang=”java”]
scala> 1.to(5).foldLeft(1)((x,y) => x * y)
res23: Int = 120
[/code]

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.

Currying

Currying transforms a function that takes multiple parameters into a chain of functions each taking a single parameter. We have seen increaseByFactor taking 2 parameters- the value to be incremented and the factor by which to increment. The curried version of the same would be:

[code lang=”java”]
scala> def curriedIncrement(factor:Int) = (x:Int) => factor * x
curriedIncrement: (factor: Int)(Int) => Int

scala> val incrementBy5 = curriedIncrement(5)
incrementBy5: (Int) => Int =

scala> println(incrementBy5(10))
50

scala> val incrementBy2 = curriedIncrement(2)
incrementBy2: (Int) => Int =

scala> println(incrementBy2(10))
20
[/code]

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.

We already saw currying being used in the above example when we used foldLeft:

[code lang=”java”]
scala> 1.to(5).foldLeft(1)((x,y) => x * y)
res23: Int = 120
[/code]

These are some of the basic concepts which would help any Java programmer to get started with the Functional concepts of Scala.

Filed Under: Scala Tagged With: scala

Using Apply and Unapply Methods in Scala

July 7, 2012 by Mohamed Sanaulla Leave a Comment

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:
[code lang=”java”]
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+"/"+this.denominator
}

//the below construct is the companion object for Fraction class.
object Fraction{

}

[/code]

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:
[code lang=”java”]
val fraction1 = Fraction(3,4)
[/code]
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:
[code lang=”java”]
val fract1 = Fraction(3,4)
val fract2 = Fraction(2,4)
val Fraction(numer, denom) = fract1 * fract2
println("Numerator: "+numer+" Denominator: "+denom)
[/code]
the above code invokes the unapply() method behind the scenes.

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 tuple.

Lets add those methods in the Fraction object
[code lang=”java”]
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)
}

}
[/code]

Check this 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:
[code lang=”java”]

object Main extends App{

println(Fraction(3,4) * Fraction(2,4) )

val Fraction(numer, denom) = Fraction(1,4) * Fraction(4,5)

println("Numerator: "+numer+" Denominator: "+denom)
}

[/code]

The output:
[shell]
6/16
Numerator: 4 Denominator: 20
[/shell]

Lets see other examples of how the apply and unapply methods can be used. There’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.
[code lang=”java”]
object Name{
def unapply(input:String) = {
val pos = input.indexOf(" ")
if ( pos == -1 ) None
else Some(input.substring(0,pos), input.substring(pos+1))
}
}

object Main extends App{

val personName = "FirstName LastName"
val Name(firstName, lastName) = personName
println(firstName+" Last: "+lastName)

}
[/code]
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.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

Filed Under: Scala Tagged With: scala

Traits in Scala- Advanced concepts

July 6, 2012 by Mohamed Sanaulla Leave a Comment

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.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

[code lang=”java”]
trait Reader{
def read(source:String):String
}

trait StringReader extends Reader {
override def read(source:String) = {
Source.fromString(source).mkString
}
}
[/code]

We have seen previously about adding trait to the class declaration, but that’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.

Now lets look at an example to mixin a trait while creating object:
[code lang=”java”]
class Person(var name:String, var age:Int){
def getDetails = name+ " "+ age
}

class Student(name:String, age:Int, var moreDetails:String)
extends Person(name,age) with Reader{

override def getDetails = {

val details = read(moreDetails)
"Student details\n"+name+
" "+age+"\n"+"More: "+details

}

}
[/code]
Lets create an instance of above Student class without including the StringReader trait.
[code lang=”java”]

object Main extends App{

val student1 = new Student("Sana", 20,
"About the student")

println(student1.getDetails)
}

[/code]
The output would be:
[code lang=”java”]
Student details
Sana 20
More: DEFAULT
[/code]
Really not useful, the Reader trait is not enough, so we make use of adding a trait during object creation:
[code lang=”java”]
object Main extends App{

val student1 = new Student("Sana", 20,
"About the student") with StringReader

println(student1.getDetails)
}
[/code]

The output:
[shell]
Student details
Sana 20
More: About the student
[/shell]

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:
[code lang=”java”]
import scala.io.Source
trait Reader{
var source = "DEFAULT"
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+ " "+ age
}

class Student(name:String, age:Int, moreDetails:String)
extends Person(name,age) with Reader{

source = moreDetails

override def getDetails = {
val details = read
"Student details\n"+name+" "+age+"\n"+"More: "+details
}
}

object Main extends App{

val student1 = new Student("Sana", 20,
"About the student") with StringReader

println(student1.getDetails)
}
[/code]
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 source field in the trait.

Layering Traits

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.
[code lang=”java”]
trait FileReader extends Reader{

override def read(source:String) = {
Source.fromFile(source,"UTF-8").mkString
}
}

trait UrlReader extends Reader{

override def read(source:String) = {
Source.fromURL(super.read(source),"UTF-8").mkString
}
}
[/code]
Interesting to see super.read(source) in the UrlReader trait. Does that mean it inokves the read(source) in Reader trait? We wouldn’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:
[code lang=”java”]
object Main extends App{

//case 1
val student2 = new Student("Stud1",20, "/tmp/url")
with FileReader with UrlReader

println(student2.getDetails)

//case 2
val student3 = new Student("Stud2",20,"https://javabeat.net")
with StringReader with UrlReader

println(student3.getDetails)
}
[/code]
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.
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.

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.

Another interesting concept to explore is how the traits are mapped to the classes which the JVM can consume.
A trait with abstract method:
[code lang=”java”]
trait Reader{
def read(source:String):String
}
[/code]
translates to a usual Interface in Java
[code lang=”java”]
Compiled from "TraitTrans.scala"
public interface Reader {
public abstract java.lang.String read(java.lang.String);
}
[/code]

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
[code lang=”java”]
trait Reader{
def read(source:String):String
}

trait StringReader extends Reader{
import scala.io.Source
def read(source:String) =
Source.fromString(source).mkString
}
[/code]
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
[code lang=”java”]
mohamed@mohamed-Aspire-4710:~/scalaP$ javap -c StringReader.class
Compiled from "TraitTrans.scala"
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
}
[/code]
One can make out that the companion class generated contains the method implementations. Here is a superb description of how the traits and classes extending traits get translated to the classfiles for the JVM.

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.

Filed Under: Scala Tagged With: scala, scala traits

Traits in Scala

July 5, 2012 by Mohamed Sanaulla Leave a Comment

Java doesn’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’t contain any implementations. (This is going to change with Defender Methods in Java 8). Lot of other languages support interface like constructs but with greater power. And one such construct in Scala are Traits.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

Traits like Interfaces in Java

Lets have a look at Trait being used as a Interface in Java. Consider a Trait Reader which provides a abstract read method.
[code lang=”java”]
trait Reader{
def read(source:String):String
}
[/code]
This trait can be extended by Scala classes like:
[code lang=”java”]
class StringReader extends Reader{
import scala.io.Source
def read(source:String) =
Source.fromString(source).mkString
}
[/code]
In Scala we can place imports at any line. Lets see the above code in action:
[code lang=”java”]
object Main extends App{
val stringReader = new StringReader
println(stringReader
.read("This is a string to be printed back"))
println(stringReader.isInstanceOf[Reader])
}
[/code]
The output is:
[shell]
This is a string to be printed back
true
[/shell]

You must be thinking: But this is what an Interface can do, how is a trait different?

Traits with method implementations

Let me edit the Reader trait to implement read method to read the contents from the String i.e what StringReader does.
[code lang=”java”]
trait Reader{
def read(source:String):String =
Source.fromString(source).mkString
}
[/code]
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 DRY. Java is introducing a similar concept in Java 8 called Defender Methods. The main intention of introducing Defender Methods is for enhancing the APIs in such a way that it doesnt break millions of existing implementations.

Lets mix in the above trait into a class.
[code lang=”java”]
class Person(var name:String, var age:Int){
def getDetails = name+ " "+ age
}

class Employee(name:String, age:Int, var moreDetails:String)
extends Person(name,age) with Reader{

override def getDetails = {
val details = read(moreDetails)
name + " "+age+"\n"+"More: "+details
}

}
[/code]
We have a Employee class which extends Person class and mixes in the Reader trait. Just like in Java we use implements keyword, in Scala we use with 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 read method in the Reader trait can be invoked from the Employee class just as if the method was actually a part of Employee class.

Lets see the above classes in Action:
[code lang=”java”]
object Main extends App{

val employee1 = new Employee("Alex",20,
"Some more details as string")

println(employee1.getDetails)
}
[/code]
The output:
[shell]
Alex 20
More: Some more details as string
[/shell]

These were some of the basic concepts of Traits. There’s lot of things yet to be explored, I think I will cover the advanced concepts in a subsequent article.

The complete code for the above example:
[code lang=”java”]
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+ " "+ age
}

class Employee(name:String, age:Int, var moreDetails:String)
extends Person(name,age) with Reader{

override def getDetails = {
val details = read(moreDetails)
name + " "+age+"\n"+"More: "+details
}

}

object Main extends App{

val employee1 = new Employee("Alex",20,
"Some more details as string")

println(employee1.getDetails)
}
[/code]

Filed Under: Scala Tagged With: scala

Inheritance and Overriding in Scala

July 4, 2012 by Mohamed Sanaulla Leave a Comment

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 “override” modifier. In Java one can use the @Override annotation to enforce correct overriding
  • 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 here to know more about Primary and Auxiliary constructors in Scala

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

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.

Inheritance in Scala

Just like in Java, classes in Scala can extend other classes using the extends keyword. And Scala also doesn’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).

Suppose we have a Item class which has two fields- price and description:
[code lang=”java”]
class Item(var price:Double, var description:String){
override def toString():String = {
description+" Cost: "+price
}
}
[/code]
Every class in Scala are subclasses of AnyRef, 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 AnyVal. The toString() method is defined in AnyRef class and hence we use the override modifier when we override that method.

Lets have a SpecialItem class which extends Item.
[code lang=”java”]
class SpecialItem(price:Double, description:String)
extends Item(price,description){
}
[/code]
As I said before the constructor of the super class can be invoked only from the Primary Constructor of the sub class. From here 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.

Lets create an instance of both these types and print their contents:
[code lang=”java”]

object Main extends App{
val item = new Item(45.6,"Book")
println(item)
//Book Cost: 45.6
val specialItem = new SpecialItem(56.8,"Sepcial Book")
println(specialItem)
//Sepcial Book Cost: 56.8
}
[/code]

Now that we have seen how classes can be extended in Scala, lets have a look at the restrictions related to overriding.

Overriding def’s

In Scala methods are declared by using “def” 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.
[code lang=”java”]
class Item(var price:Double, var description:String){
//No discount for Item
def discountedPrice():Double = price

override def toString():String = {
description+" Cost: "+discountedPrice()
}
}
class SpecialItem(price:Double,
description:String,
var discountPercent:Double)
extends Item(price,description){
//Discounted price
override def discountedPrice():Double = {
price – ((discountPercent/100) * price)
}
}
[/code]

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:
[code lang=”java”]
object Main extends App{
val item = new Item(45.6,"Book")
println(item)
//Book Cost: 45.6
val specialItem = new SpecialItem(56.8,"Sepcial Book", 10)
println(specialItem)
//Sepcial Book Cost: 51.12
}
[/code]

Some restrictions related to Overriding:
– Cannot override a var with a val or def, doing this is an error:
[code lang=”java”]
class Item(var price:Double, var description:String){
var discountedPrice = price

override def toString():String = {
description+" Cost: "+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)
}
}
[/code]
In case there the var in super class is abstract then it can be overridden in the subclass.
– A val in Superclass cannot be overridden by var or def in subclass.

Overriding def with var

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:
[code lang=”java”]
class Item(var price:Double, var description:String){
def discountedPrice_=(discPrice:Double){ price = discPrice}
def discountedPrice = price

override def toString():String = {
description+" Cost: "+discountedPrice
}
}

class SpecialItem(price:Double,
description:String,
override var discountedPrice:Double)
extends Item(price,description){
}
[/code]
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:
[shell]
InheritanceTest.scala:10: error: overriding method
discountedPrice in class Item of type => Double;

variable discountedPrice needs `override’ modifier

class SpecialItem(price:Double,
description:String,
var discountedPrice:Double)
^
one error found
[/shell]

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.

Filed Under: Scala Tagged With: scala

Primary and Auxiliary Constructors in Scala

June 29, 2012 by Mohamed Sanaulla Leave a Comment

Introduction to Scala Constructor

Constructors in Scala are a bit different than in Java. Scala has 2 types of constructors:

  • Primary Constructor
  • Auxiliary Constructor

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

Primary Constructor

In Java we have a no-args default constructor which is provided for every class which doesn’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.

In Scala constructors, 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.

[code lang=”java”]
class Employee{
var age:Int = 20
}
[/code]

In the above example the primary constructor didn’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.

[code lang=”java”]
class Employee(val firstName:String,
val lastName:String){

override def toString():String = {

&quot;First Name: &quot;+firstName+&quot; Last Name: &quot;+lastName
}
}
[/code]

Auxiliary Constructor

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 this.
Lets see an example:

[code lang=”java”]
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
}

}
[/code]

There’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:

[code lang=”java”]
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
}

}
[/code]

Trying to compile the above code results in:

[shell]
$ scalac Employee.scala
Employee.scala:9:error: called constructor’s definition must
precede calling constructor’s definition
this(firstName, lastName, city)
^
one error found
[/shell]

The error clearly says what’s wrong. One would have to take care of this, though the compiler would report such issues, but its always good to know.

Filed Under: Scala Tagged With: scala

Package Objects in Scala

June 28, 2012 by Mohamed Sanaulla Leave a Comment

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.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

Let’s take a look at very simple example.

[code lang=”java”]
//File: TestClass.scala
package net{

package javabeat{

class TestClass{

def instanceMethod():String = {
println("From TestClass: "+packageMethod1)
"Invoked instance method"
}

}

object TestClass extends App{

val testObj = new TestClass
println(testObj.instanceMethod)

println(packageMethod1)

println(packageField1)
}
}
}

package net{

package object javabeat{

def packageMethod1():String = {
"Invoked Package Method1"
}

val packageField1 = "Package Field1"
}
}
[/code]

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’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.

In the above example we declared a package object using the syntax package object. We declared a method packageMethod1 and a field packageField1 in the package object javabeat. In the class TestClass defined in the package net.javabeat we try to access the method defined in the package object.

Someone very new to Scala would wonder about the following code:

[code lang=”java”]
object TestClass extends App{

val testObj = new TestClass
println(testObj.instanceMethod)

println(packageMethod1)

println(packageField1)
}
[/code]

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.

In short the methods, fields declared in the package object are accessible throughout the package.
Lets compile and run the above code:

[shell]
$ scalac TestClass.scala
$ scala net.javabeat.TestClass
From TestClass: Invoked Package Method1
Invoked instance method
Invoked Package Method1
Package Field1
[/shell]

If you get the following error:

[shell]
TestClass.scala:15: error: not found: type App
object TestClass extends App{
^
one error found
[/shell]

Then you need to use the latest Scala version or you can replace extends App with extends Application.

Filed Under: Scala Tagged With: scala

Fields which satisfy JavaBean specification – BeanProperties in Scala

June 26, 2012 by Mohamed Sanaulla Leave a Comment

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.

also read:

  • Primary and Auxiliary Constructors in Scala
  • Traits in Scala
  • Java HelloWorld vs Scala HelloWorld

BeanProperties in Scala

Let’s have a look at some code:

[code lang=”java”]
import scala.reflect.BeanProperty
class Book{
@BeanProperty var title:String = _
@BeanProperty val isbn:String = "ISBN10"
}
[/code]

Let’s compile the above code and use javap to inspect the bytecode.

[shell]
$ scalac Book.scala
$ javap Book.class
Compiled from "Book.scala"
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();
}
[/shell]

The field which was declared with var keyword would have a getField and setField generated where as the field declared with val keyword would have only a getField generated. We already know from here the difference between val and var.

In the above example, title is declared as var and isbn is declared as val. Hence there are getters and setters assocaited with title field and only getter associated with the isbn field.

Filed Under: Scala Tagged With: scala

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved