Friday, November 28, 2014
This article provides a quick introduction on using variables in Scala.

Mutable Variables

In Scala var keyword is used to declare mutable variables whose value can be changed.

var iInt : Int = 30

Scala supports type inference where the Scala compiler infers the type of the variable based on the value assigned. For example, the above variable declaration could be simply written as,

var iInt = 30

In Scala type specification follows the variable name unlike other programming languages. There are no primitive types like Java and all data types are objects.

Immutable Variables

In Scala val keyword is used to declare immutable variables whose value cannot be changed. These are constants.

val cDouble : Double = 20.0

Again explicit type specific is not necessary and can be ignored.

val cDouble = 20.0

Using val in Scala is same as using final keyword to defined constants in Java.

Lazy Val

Scala has in-built support for Lazy initialization using lazy val. This allows to declare immutable variables whose value is computed on demand. Let us look at a simple example.

A simple Scala class.

class LazyMe {
    println("LazyMe is initialized now");
    
    def print() {
      println("In LazyMe");
    }
}

A simple Scala object which creates and instance of LazyMe class.

object ScalaVarTest {
  def main (args : Array[String]) {
    // Lazy initialization
    // Immutable variable with value computed on demand
    lazy val lazyMe : LazyMe = new LazyMe
    println("LazyMe is not initialized yet")
    lazyMe print
  } 
}

This example produces the following output.
LazyMe is not initialized yet
LazyMe is initialized now
In LazyMe

Note that when declared as lazy val an instance of LazyMe is created only when there is real need, in this example when print method is called.

Proceed to read other Scala Tutorials.

1 comment :

  1. nice article well explain. you can also visit is link for more details

    http://www.javaproficiency.com/2015/11/scala-variables.html

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top