Language tour¶
Learn the basics through four short programs. Run each one before moving on, then change a value or add a statement. The examples introduce one idea at a time.
Variables¶
A variable is a named box that holds a value. let can be changed later. const cannot.
import system;
fun main() { // (1)
let name = "Ada"; // (2)
const n = 3; // (3)
name = "Grace"; // (4)
System.println(name); // (5)
System.println(n);
}
- Every program starts in
main. let— Dream infersnameis astringfrom"Ada".const—nis locked after this line.- Reassign a
letwith=. - Print a line to the terminal (
System.printlnafterimport system;).
You can write the type yourself when you want: let score: int = 10;.
See Variables.
Control flow¶
Control flow chooses which lines run, and how often.
import system;
fun main() {
let score = 85;
if score >= 90 { // (1)
System.println("A");
} else if score >= 70 {
System.println("B");
} else {
System.println("C");
}
let i = 0;
while i < 3 { // (2)
System.println(i);
i = i + 1; // (3)
}
}
- Parentheses around the condition are optional. The condition must be a
bool(trueorfalse). whilerepeats the block as long as the condition is true.- Change
ior the loop never ends.
for (let i = 0; i < 3; i = i + 1) is another way to count. for (let x in list) walks a collection.
See Control flow.
Functions¶
A function is a named recipe. You pass values in; it can return a value out.
import system;
fun greet(name: string): string { // (1)
return "Hello, " + name; // (2)
}
fun main() {
let msg = greet("world"); // (3)
System.println(msg);
}
fun, then the name, thenname: typeparameters, then: ReturnType.+on strings glues them together.- Call
greetwith"world";msgis"Hello, world".
fun main() has no return type — it returns nothing.
See Functions.
Lists¶
A list grows as you add items. Import system.collections for List.
import system;
import system.collections; // (1)
fun main() {
let xs = List<int>(); // (2)
xs.push(10); // (3)
xs.push(20);
for (let n in xs) { // (4)
System.println(n);
}
}
List,Map, andSetlive in this package.List<int>()— an empty list that only holds integers.pushadds at the end.for..insetsnto each element.
See Arrays and Collections.
What next?¶
Next steps — reference, cookbook, and community.