On Fri, 19 Jun 2009, nikhil wrote:

> 
> 
>  Hi,
> 
> Does anybody know what Symbol Literals, in Scala, are used for ?
> >From the book all I gather is that are they interned, like Java strings, and 
> >the syntax is 
> cheaper [ only a single quote :) ]
> 
> I mean why cant we just use String literals instead ?
> 
> Does it offer any advantages over strings or is it just used because its a 
> short hand for strings ? 
> 
> Regards,
> Nikhil
> 

The concept of 'Symbol Literals' is best understood from a
functional programming perspective.

In simple words it means an 'atom' or a literal used for
symbolic evaluation (usually a pattern match).

In the Scala world, 'Symbol Literal' is also known as 'Case
class' !

Here is an example that should help:


%%% code written in erlang %%%

-module(geometry).

-export([area/1]).

area({rectangle, W, H}) ->
        W * H;
area({circle, R}) ->
        3.14159 * R * R.


Do you notice that the area() function has 'rectangle' and
'circle' specified ?

Both 'rectangle' and 'circle' are Symbol Literals or atoms,
which serve purpose of pattern matching each of the specific
code blocks.

The same type of code in C++ can be written as:

#define RECTANGLE 1
#define CIRCLE    2

int type = some_fun();

switch(type)
{
    case RECTANGLE:
        ....
        break;

    case CIRCLE:
        ....
        break;
}

What is the purpose of RECTANGLE and CIRCLE here ? They are just
used as atoms.

Hope this helps build up the concept in a nice fashion.

Let me know.


thanks
Saifi.

Reply via email to