Expressions
Primary expressions
Literals, names, this, parentheses, array and range literals, lambdas and string interpolation, the building blocks of every other expression.
since 0.1.0-alpha.1linuxwindowswasm
Description
A primary expression is the smallest unit an operator or a call can act on:
| form | meaning |
|---|---|
42 3.14 "s" true false |
a literal |
name |
a local variable, a parameter, a member, a function or a type |
this |
the enclosing instance, or the receiver value inside a method of a primitive type |
(expr) |
grouping |
[e1, e2, ...] |
an array literal; a range inside the brackets is spread into its elements |
a .. b |
a range value, both endpoints included |
(p1, T2 p2) => expr R (p1, T2 p2) => expr |
a lambda; each parameter is written without a type or as Type name (a union too: int | string p), an optional return type R comes before the parameter list, and it captures the variables it uses |
await expr |
a suspension point that parks the current task until expr completes |
inject Type |
an explicit injection selector for Type |
Literals, grouping, arrays, ranges and lambdas
use io::console;
class Sink {
int total = 0;
Sink (<<)(int n) {
total = total + n;
return this;
}
}
void apply((int) => void f) {
f(5);
}
void main() {
int x = 5;
console.writeln((x + 1) * 2);
Array<int> listed = [10, 20, 30];
Array<int> spread = [1..4];
console.writeln(listed);
console.writeln(spread);
var inc = (int n) => n + 1;
console.writeln(inc(4));
var sum = (int p, int q) => {
int t = p + q;
return t * 2;
};
console.writeln(sum(1, 2));
console.writeln(listed.filter(bool (v) => v > 15));
Sink sink = Sink();
apply((n) => sink << n);
console.writeln(sink.total);
}
main();
12
[10, 20, 30]
[1, 2, 3, 4]
5
6
[20, 30]
5
Rules
- A lambda body is either an expression (
(x) => x + 1) or a statement block ((x) => { ...; return y; }). - A lambda may write its return type before its parameter list:
bool (i) => i % 2 == 0,Foo? (int k) => lookup(k),int | string (int k) => { ... }. A function type is written in parentheses:((int) => int) (int a) => (int b) => a + b. The expression body, or everyreturn, is checked against the written type as a named function's body is, including the numeric return boundary:float (int n) => n / 2returns1.0e0for3. Without a written type the return type comes from the body. - Where the lambda has a target type, a written return type must be the target's return type or a subtype of it:
(int) => Animal f = Dog (int x) => Dog();is accepted, and(int) => float g = int (int n) => n;is a compile error (lambda return type 'int' does not match 'float', ...); numbers do not convert between function types. - A written return type binds a generic callee's type parameter exactly, in method and constructor calls:
xs.map(string (x) => "n" + x)isxs.map::<string>((x) => "n" + x). Among overloads, a lambda with a written return type applies only to a parameter whose return type accepts it. - An untyped parameter takes its type from the target. A lambda with no target, such as the initializer of a
var, must declare the type of every parameter:var id = (x) => x;andvar t = int (x) => x;are compile errors (lambda parameter 'x' needs a type: ...). - The target reaches into both arms of a conditional, every arm of a
matchand both operands of??:(int) => int k = c ? (x) => x + 1 : (y) => y;types both lambdas. An arm that does not fit the target is a compile error at the arm (conditional arm has type 'string', expected 'int'). A type parameter already bound to a function type is a target too: withArray<(int) => int> fs,fs.add((x) => x * 2)typesxasint. Name? ( params ) => bodyfollowed by:is read as the?of a conditional. An optional-return lambda used as a conditional's true arm is written in parentheses:b ? (Foo? (int k) => lookup(k)) : h. In the false arm it needs none:b ? h : Foo? (int k) => lookup(k).- A lambda checked against a function type, such as a parameter, a variable or a return type, must not declare more parameters than that type passes. Passing
(int a, int b) => a + bwhere(int) => intis expected is a compile error. - A lambda with no target type, such as the initializer of a
var, has a function type: the declared parameter types and its written return type, or the type its body returns.var l = (string s) => s.length();makesla(string) => int, so(int) => int h = l;is a compile error (seelang.type-expressions), and a call throughlchecks its arguments:l(5)is a compile error. A block body with noreturnvalue returnsvoid, sovar p = (int a) => { console.writeln(a); };makespan(int) => void. A result the body does not determine, such as a block body that only throws, is not checked. - A block body with no target type whose
returnstatements give values of different types returns their merge (lang.merged-types): returns ofDog()andCat()giveAnimal, and a bare literal beside a typed return takes its type. Returns with no common type, such asBox()andNoneor1and"one", are a compile error; write the return type:var find = Box? (int k) => { if (k > 0) { return Box(); } return None; };. Two spellings of one type, such asFooandNs::Fooafteruses Ns;, are the same type. Where the lambda has a target type, eachreturnis checked against the target's return type instead. - An expression body in a position where the lambda must return
voidis treated as a statement: its value is discarded, exactly like an expression statement. That is whyapply((n) => sink << n)is legal even though<<returns its receiver. A block body that returns a value wherevoidis expected is still an error, and a lambda whose expected return type is notvoidhas its body checked against that type. - A block body must return a value on every path that reaches its end when the lambda's expected return type is not
void: falling off the end of the block, or a barereturn;, is a compile error (lambda body does not return a value on every path). A path that cannot reach the end, because it throws or loops forever (while (true)with nobreakthat leaves it), needs noreturn. A block body that returns a value on some paths and none on others is an error wherever the lambda is used. - A lambda captures a primitive local variable (
int,float,bool,string) by snapshot: a later change to the variable is not seen by the lambda. A struct or collection local (Array,Map,Set) is captured by copy the same way, and a class instance by reference (the object is shared). To share mutable state, capture an object and change its fields. - A lambda cannot write a captured local. Inside a lambda body, assigning a local of an enclosing function or lambda (
n = 1,n += 1), storing into a field or element of a captured value (p.x = 1with a structp,xs[0] = 1,m["k"] = 1), and calling amutatingmethod or a collection verb on a captured value (p.bump(),xs.add(1),m.set("k", 1)) are compile errors (cannot assign to captured 'n' in a lambda: the lambda captured 'n' by copy, ...). Such a write would change only the lambda's copy. Return the new value from the lambda and assign it outside, or (oncerefparameters land) take the variable as arefparameter. This changes behaviour for existing programs: such writes used to compile and were silently lost. The rule applies at any depth: a nested lambda that writes a local of an enclosing lambda or function is an error too, and so is a write in a block factory (bind T { ... }), which runs as a lambda (lang.dependency-injection). - Which writes count is decided by the declared type, never by what the variable holds at run time. A store into a field or element of a captured struct,
Array,MaporSetis a write to the capture, including a store through a struct'sset ([])indexer (b[0] = 7,b[1] += 5), as it is for aconststruct (lang.const). Amutatingcall or a collection verb is a write to the capture when its receiver's declared type is a value type, an interface or an optional (ib.add(1)withIB ib,ob?.add(1)withIB? ob,it.add(1)withIIterable<int> it), also when it holds a class instance. This changes which programs compile. Through an interface the error also names the remedy for a value that holds a class instance: narrow it to that class first, or capture a class-typed variable. A receiver whose declared type is a class, or an optional of a class, holds a shared object (or nothing), so a store into its fields and any call on it,mutatingor not, are allowed (box.value = 1,box.xs.add(1),mc.bump(),om?.bump()withC? om); rebinding the captured variable itself (om = C()) is still an error.constandreadonlyagree: amutatingcall through aconstorreadonlyclass variable or field compiles too (lang.const). Inside a class method,thisis a shared object too, so a lambda may write its fields and call its methods (count += 1,xs.add(1),bump()). Inside a struct method,thisis captured by copy like any struct: a field write, an indexer store or amutatingcall on it in a lambda (n += 1,this.n = 1,xs.add(1),bump()) is the same error (cannot assign to captured 'this' in a lambda: ...). This changes behaviour for existing programs: those writes compiled and were lost. Writes to the lambda's own parameters and locals and a nested lambda's, and to globals, which are not captured, are allowed. A write through a value typed by a type parameter (x.add(1)withT x) is not checked in the generic body; it is reported where the compiler specializes the body for a binding that makes it a write (type 'P' bound to 'T' of 'k' does not fit its use: cannot call mutating method 'bump' on captured 'x' in a lambda: ...), a gap that bounds on type parameters close. thisis available only inside a class body; using it elsewhere is a compile error.- A range
a .. bincludes both endpoints. Inside array brackets the range is spread:[1..4]is[1, 2, 3, 4]. - Several keywords (
get,set,is,inand others) may be used as member names after.or::and as method names after a return type. They are keywords only at the start of a statement or declaration.
String interpolation
"...${expr}..." inserts the text of expr into the string. It works in both quote styles and is shorthand for concatenating the string pieces with the toString() of each hole, so a hole may contain any expression whose type has a toString().
\${writes a literal${.- A lone
$that is not followed by{is an ordinary character. - An empty hole (
${}) and an unterminated hole are compile errors. - A string literal inside a hole must use the opposite quote style from the string that contains it:
"${'has a } in it'}"is valid, while a nested literal with the same quote character ends the outer string at that point.
Interpolation
use io::console;
int x = 5;
console.writeln("x=${x}, next=${x + 1}");
console.writeln("literal \${x} and a $ sign");
console.writeln("${'has a } in it'}");
console.writeln('${"double quotes inside"}');
x=5, next=6
literal ${x} and a $ sign
has a } in it
double quotes inside
Examples
A lambda captures primitives by snapshot and objects by reference
use io::console;
class Box {
int n = 0;
}
void main() {
int seen = 0;
var bump = (int v) => v + 1;
seen = bump(seen);
seen = bump(seen);
console.writeln(seen);
Box box = Box();
var inc = () => { box.n = box.n + 1; };
inc();
inc();
console.writeln(box.n);
int base = 10;
var add = (int x) => x + base;
base = 100;
console.writeln(add(1));
}
main();
2
2
11
Keywords as member names
use io::console;
class Gate {
int in = 3;
bool is() => true;
int get() => 7;
}
Gate g = Gate();
console.writeln(g.in);
console.writeln(g.is());
console.writeln(g.get());
3
true
7
Notes
- A variable that holds a function value, such as
var inc = (int n) => n + 1;, is called withinc(4)inside a function body. Declare such variables inside a function. vardeclarations infer the type from the initializer. They are accepted in function bodies, in the body of a control statement, at the outermost level of a script and in a namespace body.awaitandinjectare covered with the features they belong to (tasks and dependency injection).