在Dart中,函数和getter之间有什么区别?

huangapple go评论59阅读模式
英文:

What is the difference between a function and getter in Dart?

问题

从函数中获取值,我可以这样做:

bool goOutside() {
    if (今天是个好天气) {
        return true;
    } else {
        return false;
    }
}

但我也可以这样做:

bool get goOutside {
    if (今天是个好天气) {
        return true;
    } else {
        return false;
    }
}

有人能告诉我它们之间的区别吗?哪一个是*‘正确’*的,或者它们分别适用于哪些用例?

英文:

To get a value from a function I can to this:

bool goOutside() {
    if(today is a good day){
      return true;
    }else{
      return false;
    }
  }

But I can also do this:

bool get goOutside {
    if(today is a good day){
      return true;
    }else{
      return false;
    }
  }

Can someone tell me the difference between those? Which one is the 'right' one or for what use cases are they are good?

答案1

得分: 2

代码调用的语法不同。对于get,你只需使用print(goOutside);,但对于函数,你需要使用()运算符,如print(goOutside());。这也意味着函数可以在参数列表中接受参数,而getter则不行。

我会选择使用getter而不是不接受参数的函数,因为这样可以得到更清晰、易维护的代码。然而,如果代码涉及IO操作或可见于程序的副作用,我会选择函数,以便明确表达这一点,避免难以找到的错误。

**免责声明:我不是Dart专家。这个答案是推测性的。

英文:

The syntax for invoking the code is different. In the case of the get you would just use print(goOutside); but in the case of the function you would call with the () operator as in print(goOutside());. This also means the function can accept parameters in the arguments list but the getter cannot.

I would go for a getter instead of a function that accepts no parameters as this could result in cleaner and more maintainable code. However if the code has any funny business such as IO or program-visible side-effects I would go for the function to make this clear and avoid hard to find bugs.

Disclaimer: I am not a Dart expert. This answer is speculative.

huangapple
  • 本文由 发表于 2023年4月6日 23:53:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定