Declarations, Blocks, Scope, and Qualification

Types of Declarations

In Scala we can declare variables and constants:

var balance: Double = 100.0
val pi: DOuble = 3.14

In this example balance is the name of a container that currently contains 100.0.

The content of the container can be changed using an assignment command:

balance = 10.0 + balance // now balance contains 110.0

By contrast, pi is a constant that can't be changed:

pi = 10.0 + pi  // error

We can also declare methods, objects, and classes in Scala:

class Gladiator {
  var health: Int = 100
  def attack(opponent: Gladiator): Unit = {
     val damage = 5
     opponent.health = opponent.health – damage
  }
}

object Tournament {
  def main(args: Array[String]): Unit = {
     val fang: Gladiator = new Gladiator()
     val zing: Gladiator = new Gladiator()
     fang.attack(zing)
     zing.attack(fang)
  }
}

Blocks and Scope

Declarations can be global or nested in a block:

{
  int x = 10;
  int y = 20;
  {
     int x = 5;
     int z = 30;
     x = x + 1;
     y = x + y + z;
  }
  println("x = " + x); // prints 10
  println("y = " + y); // prints 56
  println("z = " + z); // error z not visible here
}
 

The scope of a declaration is the region of the program where it is visible.

The scope of a declaration can be:

public

package

protected

private

local

The qualification Principle

The scope of a declaration should be as small as possible.