CHAPTER 3
A variable can be defined with or without initializer.
int i;
string s = "a";
If a variable declaration doesn't come with an initializer, the default value for that variable is assumed. In the case of primitive typed values, this default value is pre-defined with different value for each type. For example, a boolean variable is default to false, while a char '\0'. For Any type and Object type, null is the default value.
In Julian, a variable defined outside any compound types and functions is considered to be global variable. Global variables can be accessed by other global functions, but not by any methods, which are defined inside types. This restriction is to intentionally discourage the mixed use of OO-programming and loose scripting.
int i = 5;
void fun(){
i++; // fun(), a global function, has access to i.
}
fun();
Console.println(i); // 6
Julian uses nested lexical scope. A variable defined in inner scope shadows the one of same name defined outside. Thus type incompatibility between these two is not an issue.
int i = 5;
{ // Introduce a new scope
string i = "a";
Console.println(i); // "a"
}
Console.println(i); // 5
Variables are assigned by assignment expression. During assignment an implicit type conversion may happen between certain primitive types. For compound types, however, the general hierarchy-based rules apply. A variable of certain type can be assigned to another only if the latter is of the same type, or a parent class or interface of the assigner. We will cover more about assignment to class typed variable in Class.
int i = 5.7; // implicitly cast to integer.
Console.println(i); // 5
Last, use const
to add immutability to variables. But note this only applies invariance to on-stack value. It remains legitimate to change the field or element of a const variable.
const string s = "xyz";
s = "uvw"; // throws runtime exception