Use static variable in function()

后端 未结 4 2027
谎友^
谎友^ 2021-01-12 14:11

I would know if we can declare a static var in a function, as we can do in JavaScript.

When I callback my function, my variable keep her last affectation.

Or

4条回答
  •  天涯浪人
    2021-01-12 14:50

    You can use Closures, in this example I have created a counter as follows:

    void mian(){
     var my_counter = counter(5);
     for (var i = 0; i < 10; i++) {
       print(my_counter());
     }
    }
    
    Function counter(int n) {
      var number = 0;
      var func = () {
        if (number < n) {
          number++;
          return number;
        } else {
          number = 1;
          return number;
        }
      };
      return func;
    }
    

    or also a Generator:

    Iterable count(int n) sync* {
      var number = 0;
      while (number < n) {
        yield number++;
      }
    }
    

提交回复
热议问题