Constants (const)
Constants are declared with const and cannot be reassigned after declaration. Use them for values that should never change.
Syntax
const name = value;
const name: type = value;Basic usage
class App {
const PI = 3.14159;
const MAX_USERS = 100;
const APP_NAME = "VDX";
print(APP_NAME); // VDX
print(PI * 2); // 6.28318
}Type annotations
Like variables, constants support optional type annotations:
class App {
const PI: float = 3.14159;
const MAX_SIZE: int = 1024;
const GREETING: string = "Hello";
const ENABLED: bool = true;
}Reassignment error
Attempting to reassign a constant throws a runtime error:
class App {
const MAX = 100;
MAX = 200; // Error: Cannot assign to const variable 'MAX'
}Constants vs Variables
| Feature | let | const |
|---|---|---|
| Declaration | let x = 5; | const x = 5; |
| Reassignment | Allowed | Not allowed |
| Type annotations | Supported | Supported |
| Use case | Mutable values | Fixed values |
Best practices
- Use
constfor configuration values (timeouts, limits, defaults) - Use
constfor mathematical constants (PI, E, etc.) - Use
constfor fixed strings (error messages, keys) - Use
UPPER_SNAKE_CASEnaming for constants
Example: Configuration
class App {
const API_URL = "https://api.example.com";
const TIMEOUT_MS = 5000;
const MAX_RETRIES = 3;
const VERSION = "1.0.0";
fn connect() {
print("Connecting to", API_URL);
print("Timeout:", TIMEOUT_MS, "ms");
}
connect();
}