如何撕下顶级函数,getter和setter

时间:2015-11-11 07:45:06

标签: dart

如果我有像这样的图书馆,我怎样才能创建撕下来?

main.dart

int someFunc(int x, int y) => x * y;
int get val1 => 3;
int get val2 => 4;

main() {
  // create tear-offs of someFunc, val1, and val2 here
}

1 个答案:

答案 0 :(得分:0)

当导入带有前缀的库时,这是可能的

<强> other_lib.dart

int someFunc(int x, int y) => x * y;
int get val1 => 3;
int get val2 => 4;

class OtherClass {
  int someFunc(int x, int y) => x * y;
  int get val1 => 3;
  int get val2 => 4;
}

<强> main.dart

import 'other_lib.dart' as o;

void main() {
  var _x = o#someFunc;
  var _v1 = o#val1;
  var _v2 = o#val2;

  print('_v1: ${_v1}, ${_v1()}');
  print('_v2: ${_v2}, ${_v2()}');
  print('_x: ${_x}, ${_x(_v1(), _v2())}');
}

但它也适用于同一个文件

<强> main.dart

import 'main.dart' as m;

int someFunc(int x, int y) => x * y;
int get val1 => 3;
int get val2 => 4;

void main() {
  var _x = m#someFunc;
  var _v1 = m#val1;
  var _v2 = m#val2;

  print('_v1: ${_v1}, ${_v1()}');
  print('_v2: ${_v2}, ${_v2()}');
  print('_x: ${_x}, ${_x(_v1(), _v2())}');
}

分析器尚未识别语法,但代码在VM中正常运行(前沿)。另请参阅https://github.com/dart-lang/sdk/issues/24877

在两个例子中打印

  

_v1:Closure :()=&gt;函数'get:val1'中的int:static。,3
  _v2:关闭:()=&gt;函数'get:val2'中的int:static。,4
  _x:Closure:(int,int)=&gt;函数'someFunc'中的int:static。,12