Variables and Constants
Local Variables
Section titled “Local Variables”Variables are declared by assignment. Types are inferred by default:
name = "Alice" # String, inferredage = 30 # Int, inferredExplicit type annotations use : Type after the name:
name: String = "Alice"count: Int = 0Scoping Rules
Section titled “Scoping Rules”Assignment to an unknown name creates a new variable in the current scope:
x = 10 # x created in local scopeAssignment to a known name reassigns the existing variable, regardless of which scope it lives in:
x = 10
if condition x = 20 # reassigns outer xend
puts x # 20Shadowing with var
Section titled “Shadowing with var”var explicitly introduces a new binding in the current scope, shadowing any
existing variable of the same name. The outer binding is untouched:
x = 10
if condition var x = 20 # new binding — outer x is unchangedend
puts x # 10var is also how a name is reused for a value of a different type further down the
same method. Plain assignment cannot change a variable’s type:
input = read_line # input: Stringinput = input.to_int # compile error — input is a String
var input = input.to_int # new binding — input: Int from here onConstants
Section titled “Constants”Names written in ALL_CAPS are automatically treated as constants. The compiler
enforces this and promotes the value to a readonly field or compile-time constant
in the IL:
MAX_RETRIES = 3DEFAULT_TIMEOUT = 30.0APP_NAME = "Amethyst"Assigning a namespace or type to a PascalCase name declares an alias rather than a
constant — see Aliasing.
Constants must be assigned at declaration. Reassignment is a compile error:
MAX_RETRIES = 5 # compile error — MAX_RETRIES is a constantConstants are scoped to their enclosing namespace, class, or module. Top-level constants are accessible from anywhere.
Compile-Time vs Runtime Constants
Section titled “Compile-Time vs Runtime Constants”The compiler promotes to a compile-time constant (const in IL) when the value is
a literal. Otherwise it becomes a static readonly field:
MAX_SIZE = 100 # const int MAX_SIZE = 100PREFIX = compute() # static readonly string PREFIX = compute()