Dart类中的静态调用方法(使类可调用)

cap*_*ord 2 class function call dart

对于嵌入式DSL,我希望类的行为类似于函数.对于实例来说似乎很容易(https://www.dartlang.org/articles/emulating-functions/),但我无法在课程中实现它.我尝试创建一个静态调用方法,但这也不起作用.

有没有办法或者我必须给该类另一个名称并使Pconst成为一个函数,调用构造函数?

class Pconst {
  final value;
  Pconst(this.value);
  static Pconst call(value) => new Pconst(value);

  String toString() => "Pconst($value)";
}

void main() {
  var test = Pconst(10);
  // Breaking on exception: Class '_Type' has no instance method 'call'.

  print("Hello, $test");
}
Run Code Online (Sandbox Code Playgroud)

小智 9

class TestA {
  call(int a, int b) => a + b;
}

void main()
  var TA = new TestA();

  int integer = TA(3, 4);
  print (integer); 
}
Run Code Online (Sandbox Code Playgroud)

call()方法很特殊,因为任何定义call()方法的人都被假定为动态模拟一个函数.这允许我们使用TestA它们是带有两个整数参数的函数的实例.