为什么在Dart中不能声明常量函数文字?

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

Why can't you declare constant function literals in dart?

问题

class MyClass {
  final void Function() callback;

  const MyClass(this.callback);
}

void example1() {
  const foo = MyClass(() {});
}

typedef MyVoidCallback = void Function();

void example2() {
  const MyVoidCallback bar = () {};
}
英文:

The question came into my mind when I've declared a final callback in a class, and the constructor can be declared as const, and trying to make a constant value of a function like so:

class MyClass {
  final void Function() callback;

  const MyClass(this.callback);
}


void example1() {
  const foo = MyClass(() {});
}

This gives the error:

为什么在Dart中不能声明常量函数文字?

Why can I delcare a constant constructor in the first place? What would make an object of MyClass compile-time constant if no function value can be constant?

A simpler example:

typedef MyVoidCallback = void Function();

void example2() {
  const MyVoidCallback bar = () {};
}

This gives the error:

为什么在Dart中不能声明常量函数文字?

Thank you in advance

答案1

得分: 2

由于 () {} 不是一个常量值,而是每次创建一个新实例。Dart 中的所有函数都继承自 Function 类,该类没有 const 构造函数。

但是,由于 Dart 中的函数是顶级成员,您可以通过名称传递它们(就像变量一样)。因此,如果您将函数定义在任何类之外,使其成为全局函数,您可以将其作为 const 构造函数的参数值传递。

@randal-schwartz 的评论中更新:类内部的静态函数也可以作为参数传递给这些 const 构造函数。

下面的代码应该工作正常:

class MyClass {
  final void Function() callback;

  const MyClass(this.callback);
}

void example1() {
  const foo = MyClass(doWork);
}

void doWork() {
  // TODO: do work
}

不要翻译代码部分。

英文:

It is because () {} is not a constant value, it is rather creating a new instance every time. All functions in dart inherit Function class which doesn't have const constructor.

However, since functions are top-level members in dart, you can pass them by name (like a variable). So if you define your function outside of any class such that it is a global function, you can pass it as a parameter value in a const constructor.

> UPDATE from @randal-schwartz comment: Static functions inside a class can also be passed into these const constructors as parameters.

Below code should work:

class MyClass {
  final void Function() callback;

  const MyClass(this.callback);
}


void example1() {
  const foo = MyClass(doWork);
}

void doWork() {
  // TODO: do work
}

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

发表评论

匿名网友

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

确定