() 可以对表达式进行分组:
var x = (1 + 2) * 3;
Run Code Online (Sandbox Code Playgroud)
或者可以为函数指定参数列表:
var getAnswer = () => 42;
int square(int x) => x * x;
Run Code Online (Sandbox Code Playgroud)
或者可以指定函数调用:
var answer = getAnswer();
var squared = square(4);
Run Code Online (Sandbox Code Playgroud)
or 是某些关键字语法的一部分。这包括(但不限于)if,assert,for,while,switch,catch:
if (condition) {
...
}
assert(condition);
for (var item in collection) {
...
}
while (condition) {
...
}
switch (value) {
...
}
try {
...
} on Exception catch (e) {
...
}
Run Code Online (Sandbox Code Playgroud)
[]本身创建List文字:
var list = [1, 2, 3];
var emptyList = []; // Creates a List<dynamic>.
Run Code Online (Sandbox Code Playgroud)
或者当在对象上使用时,调用operator []通常访问集合的元素:
var element = list[index];
var value = map[key];
Run Code Online (Sandbox Code Playgroud)
或在参数列表中,指定可选的位置参数:
int function(int x, [int y, int z]) {
return x + y ?? 0 + z ?? 0;
}
function(1, 2);
Run Code Online (Sandbox Code Playgroud)
或在 dartdoc 注释中,创建对其他符号的链接引用:
/// Creates a [Bar] from a [Foo].
Bar fooToBar(Foo foo) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
{}可以创建一个代码块,将行组合在一起并限制变量范围。这包括(但不限于)函数体、类声明、if-else块、try-catch块、for块、while块、switch块等:
class Class {
int member;
}
void doNothing() {}
void function(bool condition) {
{
int x = 'Hello world!';
print(x);
}
if (condition) {
int x = 42; // No name collision due to separate scopes.
print(x);
}
}
Run Code Online (Sandbox Code Playgroud)
var set = {1, 2, 3};
var emptySet = <int>{};
var map = {'one': 1, 'two': 2, 'three': 3};
var emptyMap = {}; // Creates a Map<dynamic, dynamic>
Run Code Online (Sandbox Code Playgroud)
或在参数列表中,指定可选的命名参数:
int function(int x, {int y, int z}) {
return x + y ?? 0 + z ?? 0;
}
function(1, y: 2);
Run Code Online (Sandbox Code Playgroud)
或创建枚举:
enum SomeEnumeration {
foo,
bar,
baz,
}
Run Code Online (Sandbox Code Playgroud)
或 in Strings 用于消除内插表达式的歧义:
var foo = 'foo';
var foobar = '${foo}bar';
var s = '${function(1, 2)}';
Run Code Online (Sandbox Code Playgroud)
<>当在函数或类声明中成对使用时,会创建泛型:
class GenericClass<T> {
T member;
}
T function<T>(T x) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
或在使用泛型时指定显式类型:
var map = <String, int>{};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1664 次 |
| 最近记录: |