Static call method in Dart Classes (make Classes c

2019-07-21 16:13发布

问题:

For an embedded DSL I want classes to behave like a function. It seems easy for instances (https://www.dartlang.org/articles/emulating-functions/) but I couldn't make it happen for classes. I tried creating a static call a method but this didn't work either.

Is there a way or do I have to give the class another name and make Pconst a function, calling the constructor?

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");
}

回答1:

I'd try something like this:

class _PConst{
    final value;
    _Pconst(this.value);

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

PConst(value){
    return new _PConst(value);
}

void main() {
    var test = Pconst(10);

    print("Hello, $test"); //should work ok
}

so your basically just hiding/wrapping your classes constructor behind a bog standard function.



回答2:

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

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

  int integer = TA(3, 4);
  print (integer); 
}

The call() method is special, in that anyone who defines a call() method is presumed to dynamically emulate a function. This allows us to use instances of TestA as if they were functions that take two integer arguments.