Hi Vidhya,

Val is final i mean once its initialized it cannot be changed.
whereas Var can be changed when you operate or perform calculations on it.

*In Scala Interpreter *
scala> val a=10;
a: Int = 10

scala> a=20;
<console>:5: error: reassignment to val
       a=20;
        ^

scala> var s=40;
s: Int = 40

scala> s=20;
s: Int = 20

scala> a=a+1
<console>:5: error: reassignment to val
       a=a+1
        ^

scala> s=s+1
s: Int = 21

*The reason for this can be known when you write an object like

*object SMS{
val a=10;
var b =20;
}

After compiling it run this command

javap -private SMS$

Compiled from "SMS.scala"
public final class SMS$ extends java.lang.Object implements
scala.ScalaObject{
    public static final SMS$ MODULE$;
    private int b;
    private final int a;
    public static {};
    public SMS$();
    public void b_$eq(int);
    public int b();
    public int a();
    public int $tag()       throws java.rmi.RemoteException;
}

you will observe a is final hence cannot be changed.Also

void b_$eq(int)

function is related to var b which signifies that var b is now Int as its
initialized with 20 (an int).
Now try initializing b with 20.0 then the function will be

public void b_$eq(double);

I hope this helps.

Thanks,

SMS.

On Mon, Jun 22, 2009 at 12:41 PM, Vidhya Ranganathan
<[email protected]>wrote:

>
>
> Hi all,
> Can somebody explain the difference between, Var and Val in Scala?
>
> Regards,
> Vidhya
>  
>


[Non-text portions of this message have been removed]

Reply via email to