Thursday, July 10, 2014

Understanding How :: Cons works in Scala

:: which is also pronounced as Cons is sometimes confusing to understand.  In this article let us try to understand how it works.

Before we try to understand Cons you should remember that every operation is actually a method call in Scala.  There is no such thing called operator, although the operation may falsely lead you to think that operands are being operated with an operator.

So What About + and - Operators?

You many think that simple operations such as 5 + 3 are using the + (plus) operator.  So how can we say operators are not there.

In Scala there is no primitive types.  So 5 is nothing but Int(5) and 3 is stored as Int(3).  There is a method named + in the Int class.  When we call 5 + 3 internally it calls (5).+(3), similarly 4 * 3 becomes (4).*(3).

Scala allow you to call method names with spaces and without the . (period) if there is a single parameter to the method name.  Hence (5).+(3) can be called as 5 + 3.

What About :: Cons?

:: is a special method which is used for prepending values.  Which means when you want to add a value to beginning of a list you can used cons or ::

For Example :

var names = List ("Roy","Randy","Amit")
var newNames = "Cindy" :: names

Output would be

List(Cindy, Roy, Randy, Amit)

So how does it work?  If we keep the previous discussion in mind the :: should be a method which should work on the String "Cindy".  However in reality it works on the List names.

The reason is whenever any method name is invoked it is applied on the left operand in most cases apart from those method which end with a : (colon).  In those cases the method is invoked on the right operand.

In this case this method has a name :: which ends with a : so the method is invoked on the names List.

Just remember "Cindy" :: names is interpreted as names.::("Cindy")

Hopefully this will help you to understand how cons work.

No comments:

Post a Comment