A Tour of Morfa

Variables and constants

Variable declarations

Variables in Morfa are declared using the keyword var.

var greeting: text = "Hello World";

If the initializing expression is present then the compiler is usually able to infer the type and it may be omitted:

var goodbye = "Goodbye World";

On the other hand, if there is no initializing expression then the type has to be given. The variable is then initialized to the initial value of its type (every Morfa type has an initial value).

var zero: int;

Constant declarations

Constant declarations are similar to variable declarations but we use the keyword const instead of var:

const pi = 22.0 / 7;

In Morfa, const means a compile-time constant. That is, the compiler must be able to evaluate the initializer expression during program compilation. Except for the declaration, the constant cannot be assigned, and the compiler may substitute the constant's value for each occurrence of the constant in any expression.

Local variables

A variable is local if it is declared within a function body (this is not entirely true because of inner classes, but let us simplify matters for the time being). Function parameters may be treated like local variables.

For local variables the scoping rules are similar to scoping rules in C++ or Java, with an important exception: a variable's scope does not contain its initializing expression:

var a = 1;

    var a = a + 1;   // `a` in `a+1` refers to the global `a`
    assert (a == 2);

Local variables (including function parameters) cannot be redeclared or shadowed:

func foo(a: int)
    // var a = 2; // Error: a redeclared

func bar()
    var b = 0.1;
    // var b = 0.2; // Error: b redeclared

func baz()
    var c = true;
        // var c = "not true"; // Error: c shadowed

Global variables

Global variables are declared on the module level. In contrast to local variables, the scope of a global variable is whole module, including the parts lexically before the declaration of the variable:

   x += 2;
   assert (x == 2);

var x: int;

Class and structure fields

Variables and constants may also be declared inside aggregate types (classes, interfaces and structs). Such variables become instance or static fields of enclosing types. See Chapter Classes for more information.