Archive

Archive for the ‘Scala’ Category

Null, null, Nil, Nothing, None, and Unit in Scala

Null– Its a Trait.
null– Its an instance of Null- Similar to Java null.

Nil– Represents an emptry List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents.

Nothing is a Trait. Its a subtype of everything. But not superclass of anything. There are no instances of Nothing.

None– Used to represent a sensible return value. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method.

Unit– Type of method that doesn’t return a value of anys sort.

Note: Any is supertype of AnyRef and AnyVal. AnyRef is the supertype of all the reference classes (like String, List, Iterable) in scala. AnyVal is the supertype of all the value classes (like Int, Float, Double, Byte, Short..). Null is a subtype of all the reference classes. null is its only instance. Nothing is subtype of every other type i.e of reference and value classes.

Think- AnyRef == Object in Java.

The above is a breif summary of a wonderful post by Matt Malone where he has explained all these concepts in depth with examples. Read the blog post here.

Advertisements
Categories: Scala Tags: , , , , , , ,

Traits in Scala- Deep Dive

Traits are units of code reuse in Scala. Traits encapsulates methods and field definitions. Their role is similar to that of interfaces in Java- A workaround for Multiple Inheritance. But unlike Interfaces they can have method and field definitions. More features will be explained in the article.

Defining Traits:

A trait definition looks like a class definition but uses the keyword “trait.

trait Bounceable{

     def bounce():String="Bounce Method in Trait"

}

The above declared trait has a concrete method. The ability to declare concrete methods in an trait gives default implementation option. In interfaces one has to write/copy-paste the default declaration in each class which implements the interface or declare a class that implements that interface and let other classes extend the concrete class. The first method has code repition and the second method has the restriction that a class can extend only one class. So this feature of “trait” stands out best.

As in Java a class implements interface, in Scala classes traits are mixed into a class. This is done using either extends or “with” keywords.

class Ball(s: Int) extends Bouncable{

      var size:Int

      override def toString():String= Integer.toString(size)

}

In the above example we are using extends to mix in the trait- Here Ball is implicitly inherits trait’s superclass which is “AnyRef”. Lets try to use the class Ball to test the mixed in trait.

object Test{

           def main(args:Array[String])={

                    var ball = new Ball(33)

                    var ball2:Bounceable= new Ball(400)

                    println(ball.bounce()) //This prints "Bounce Method in Trait"

                    println(ball) //This prints "33"

                    println(ball2.bounce())

                    println(ball2)

         }

}

Note: Output written as comment.

Regarding the ball2 instance being declared as type “Bounceable”. Its a valid declaration cause supertype references can refer to the instances of its subtypes. But they cannot access the methods/fields declared by the subtypes (different with the overriding case).

Read more…

How’s Scala different from Java?

  • Scala is statically type like Java but with Type Inferencing support. Which means that the scala compiler analyzes the code deeply to determine what type a particular value is.
  • In Scala its not required to use semicolons to terminate a statement if the termination is obvious by line ending. If there are more than one statements on the single line then they have to be separated by using semicolon.
  • Scala doesnot require the file containing a class definition to mirror the name of the class.
  • In Scala there’s no use of static all together. This is replaced by use of singleton object. Singleton objects are declared by using the keyword “object” and not “class”.
  • In Scala, arrays are instances of Array class and uses square brackets ([]) instead of angle brackets (<>) to indicate parameterized types.
  • In Scala the variable declaration is: “name: type”
  • Scala uses keyword “Unit” to represent functions which return “non-value” value.
  • In Scala the syntax for method declaration is different. It uses the “=” before the method body preceeded by the identifier/name of the method along with the parameter list and return type. Functions are treated like variables and constants.
  • Scala supports the use of closures, Annonymous functions- Which makes longer code simpler and shorter.

These were few things i have noted. There are lot more differences. If u know any please add it as a comment. Will upadate my post accordingly.

Categories: Scala Tags: , ,

Control Structures in Scala- A brief overview

If Statements:

Lets consider a first entry example of If statments, without using much of Scala’s features.


if(5+6==10){

println("You are wrong in calculations")

}else{

println("Keep it up")

}

This is a pretty simple and straight forward examples. Now lets add some Scala flavor in the If-Statement. In Scala If-Statements are expressions, which means that the value from If-Statements can be assigned to some variable. Lets consider another example- Finding greatest of two numbers.

Note: I am using the scala interpreter.

scala>var num1=54
num1:Int=54
scala>var num2=76
num2:Int=76

I have created 2 variables. We will have to write a If-Statement for finding out the greatest value and assign it to another variable.

scala>var big=if(num1>num2){ num1}else{num2}
big:Int=76
scala>println(big)

One can see how the result from a if-expression is assigned to a variable. This feature of If construct has removed the need of a Select case construct. Also note that the Type Inference coming into play there- I haven’t mentioned tat big is a Int but it has inferred based on the If-Statement that it will hold an Int. If we had missed the else part then it would have inferred the type to be Unit (void in Java).

For Loops

In the Scala world they are also referred to as the “For Comprehension” or “For Expression”. Let’s consider a example list.

scala> var cities=List(“Bangalore,India”, “Delhi, India”, “Chennai, India”,”Tokyo, Japan”, “New York, USA”, “London, UK”, “Paris, France”)

The above code will create a List of Cities along with their countries.  Now lets use a for loop to “comprehend” the list.


scala> for(city <- cities)println(city)

&#91;/sourcecode&#93;

Straight forward and simple. The left arrow operator (&lt;-) is called as "<strong>generator</strong>" as it is used to generate elements from the list. Now lets print the cities in India with the help of the Scala's features



scala>for(city <- cities if city.contains("India"))println(city)

Bangalore,India

Delhi, India

Chennai, India

&#91;/sourcecode&#93;

The above technique is called "<strong>Filtering</strong>". One can add multiple filers (if condition) and the filers have to be seperated by using ";".  Now suppose we want to store the Indian cities in a separate list, what do we do? Scala does have a solution to that as well. Lets look at the code:



scala> var indianCities=for(city <- cities if city.contains("India"))yield city

scala>for(city <-indianCities)println(city)

Bangalore,India

Delhi, India

Chennai, India

&#91;/sourcecode&#93;

The type of the yielded list has not been mentioned. Scala infers the type from the Type of the Collection being used to yeild a new List.

<strong>While and Do-While Loops:</strong>

While loops, as in other languages, execute the code in the block until the condition is true. Do-While is similar to While the only difference being that the loop is executed at least once and checks to see if the condition is true or not.

Example to find sum of first 10 natural numbers



scala> var i=1

scala>var sum=0

scala>while(i<=10){ sum=sum+i;i=i+1}

scala>println(sum)

An example to show do while loop:


scala>sum=0;i=0;

scala>do{ sum +=i;i+=1}while(sum<100)

scala>println(i)

That was a brief overview of If, For, While and Do-While constructs.

Categories: Scala Tags: , , , , , ,

Tuples- Returning multiple values in Scala

When I was coding in Java I used to build Classes just to return multpile values and also sometimes used pass by reference (by means of using Objects).  I really missed a permanent solution 😦 Scala has a solution for this- It supports something called “Tuples”  which is created with the literal syntax of a comma-separated list of the items inside parentheses like (x1,x2,x3 …). The items in the parantheses may not be related to each other in terms of the type, which means that we can have String’s, Int’s and so on. These literal “groupings” are instantiated as scala.TupleN instances, where the N is the number of items in the tuple. The Scala API defines separate TupleN classes for N between 1 and 22, inclusive. Tuples can be assigned to variables, passed as values or return them from the methods.

Let me explain this with an example (I have used the interactive mode of scala command):

scala> val tple=("Hello World",56, 56.66, true)
tple: (java.lang.String, Int, Double, Boolean)= (Hello, Int, Double, Boolean)

The above code creates a tuple of 4 elements of totally unrelated types.  It can be clearly seen in the result printed soon after the statement.

scala>println(tple._1)
Hello World

scala>println(tple._4)
true

It has to be noted that the parameter are referenced from 1 and not from 0. So its pretty straight forward- use <Tuple Name>._<Parameter Position> to access the element.

There are different ways of creating Tuples. Some of them are:

scala>Tuple4(5,6,"Hello",6.5)
res0:(Int,Int,java.lang.String, Double)=(5,6,"Hello",6.5)

scala>val tple1=1->2->"Hi"
tple1: ((Int,Int),java.lang.String)=((1,2),"Hi")

Observe that the tple1 contains another tuple inside it- (Int,Int). Use the same idea to access it.

scala>println(tple1._1._1)1

This was in brief about Tuples. This concept caught my attention immediately as i had faced the problem in Java. So thought of describing it here.

Categories: Scala Tags: , , ,

“val” versus “var” Declarations in Scala

Scala allows one to decide whether a variable is immutable or mutable. Immutable is Read only where as mutable is read-write. Immutable variables are declared with the keyword “val“.

scala> val age:Int=22

Here age has been initialized to a value during its declaration. As it has been declared as a val, age cannot be reassigned to a new value. Any attempt to do will result in al reassignment to val error. Let us consider an Array being declared as val.

scala> val names:Array[String]=new Array(6)

Here names reference cannot be changed to point to a different Array, but the array itself can be modified. In other words the contents/elements of the array can be modified.

scala> names= new Array(5) //This will give a reassignment to val error. 

scala> names(0)="Scala" //This does not give an error.

Also it is to be noted that val variables must be initialized when they are declared.

Mutable variables are delcared with the keyword “var“. Unlike val, “var” can be reassigned to different values or point to different objects. But they have to be initialised at the time of declaration.

scala> var age:Int=22
age: Int=22

scala> age=35
age: Int=35

There’s an exception to the rule that one must initialize the val’s and var’s. When they are used as constructor parameters, the val’s and var’s will be initialised when the object is instantiated. Also, derived classes can override val’s declared inside the parent classes.

Categories: Scala Tags: , , , ,