Search code examples
functionclasscalldart

Static call method in Dart Classes (make Classes callable)


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

Solution

  • 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.