Saturday, 7 November 2015

Scala Variables

Variable is a name of reversed memory area of any values. In scala we can declare a variable with var and val keywords.

Declare variable with var :

Variable declare with var can change value.This type variable called mutable.


var varName : datatype = Initial value

ex: var age : int = 10

or we also use below syntax to declare variable
var age =10

In this case we can change the value of age.


object variable {

def main(args: Array[String]) {
var age : Int =10;
var name = "scala";
println(" age="+age +"name ="+name);
//now we will change the values og age and name
age =30;
println("after changing the values of age and name");
println("age="+ age+"name ="+name);


age=10 name =scala
after changing the values of age and name
age=30 name =java

Declare variable with val:

Variable declare with val can not their value.This type variable called immutable.


val variableName : datatype = Initial value


val varaibleName = Initial value


object ValVaraible {
def main(args: Array[String]) {
val age : Int =10 ;
println("age="+ age);
// age = age+10 // we can not change value of val type varaibles



we can not change of value of val type variable. They behavior  like constant.

Multiple assignments:

Scala support to multiple assignments. We can assign multiple variable in a tupple.


val (var1: Int, var2: String) = Pair(10, "scala")

And the type inferencer gets it right:

val (var1, var2) = Pair(10, "java")


object mulAssign {
def main(args: Array[String]) {
val (val1: Int, val2: String) = Pair(10, "scala");
println(" val1 ="+val1 +" val2 ="+ val2);


val1 =10 val2 =scala

Variable Type:

variables in scala are three type fields , method parameter and local variables.


Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with. Fields can be both val's and var's.

Method parameters:

Method parameters are variables which values are passed to a method when the method is called. Method parameters are only accessible from inside the method - but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always val's.we can say method parameter is immutable.

Local variables:

local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both var's and val's

No comments:

Post a Comment