英文:
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:
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:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论