Scala Variables and Data Types program

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-07 19:48:06 Viewed : 225


Scala Variables and Data Types program

 Scala has two types of variables:

  •            val is an immutable variable — like final in Java — and should be preferred
  •            var creates a mutable variable, and should only be used when there is a specific reason to use it

 

Example:

Following example illustrates about Scala Variables and Data Types.

Save the file as − DataTypes.scala.

 

DataTypes.scala  //File name

package runnerdev

object DataTypes {

  def main(args: Array[String]) {

    //create variables without declaring their type

    val x = 10 //immutable

    val s = "test string"

    println("x " + x)

    println("s " + s)

 

    var a = 100 //mutable

    a = 200

    println("a " + a)

 

    // You can also explicitly declare a variable’s type

    val y: Int = 1

    val str: String = "This is a string"

    var z: Int = 11

    println("y " + y)

    println("z " + z)

    println("str " + str)

// x=11   it gives error as reassignment to val

  }

}

compile and run the above example as follows 

scala> scalac DataTypes.scala

scala> scala DataTypes

OutPut:

x 10

s test string

a 200

y 1

str This is a string

Search
Sub-Categories
Related Articles

Leave a Comment: