Categories
scala

values variables and datatypes in scala

In this post , let us learn about values variables and datatypes in scala .

Values

Values are immutable which cannot be modified . In the below example , ValuesVariablesTypes is the object created for this tutorial .

  • val – keyword (only in lower case) .
  • Int – datatype  
object ValuesVariablesTypes extends App {
    val x : Int = 43 ;
    print(x)
}
43
Process finished with exit code 0

We are trying to modifying the value in the below case . It failed with reassignment error . Hence this immutable feature will not allow us to modify the values .

object ValuesVariablesTypes extends App {
    val x : Int = 43 ;
    print(x)
    x = 44 ;
}
reassignment to val
    x = 44 ;

It is not mandatory to specify the datatype as compiler can infer datatypes automatically . And so it worked for the below case also .

object ValuesVariablesTypes extends App {
    val x = 43 ;
    print(x)
}
43
Process finished with exit code 0

Datatypes

Few of the main datatypes along with ways to specifying as follows

Datatype specify with datatype specify without datatype
String val a : String = “Hello” val a = “Hello”
Boolean val b : Boolean = false val b = false
Char val c : Char = ‘ abc’ val c = ‘ abc’
Short(2bytes of length ) val d : Short =7416 val d = 7416
Long(4bytes of length ) val e : Long = 74167416 val e = 74167416
Long (for more than 4 bytes) val f : Long = 7416741674167416L val f = 7416741674167416L
Float val g : Float = 14.0f val g = 14.0f
Double val h : Double = 3.63 val h = 3.63

Variables

Variables can be modified which is the difference between values and variables .

object ValuesVariablesTypes extends App {
    var Y = 43 ;
    println(Y)
    Y = 44 ;
    print(Y)
}
43
44
Process finished with exit code 0

Hope this post gives an idea about values variables and datatypes in scala .