如何创建一个返回 const 值的工厂构造函数

2024-01-10

是否有可能返回 as const 的不同实现?

abstract class Foo<T> {
  factory Foo(T thing) => const FooImpl(thing); // <= Arguments of a constant creation must be constant expressions
  T get thing;
}

class FooImpl<T> implements Foo<T>{
  final T thing;
  const FooImpl(this.thing);
}

Dart 有一个委托工厂构造函数来允许这样做

abstract class Foo<T> {
  const factory Foo(T thing) = FooImpl;
  T get thing;
}

class FooImpl<T> implements Foo<T>{
  final T thing;
  const FooImpl(this.thing);
}

see also

https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU and https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU https://groups.google.com/a/dartlang.org/forum/#!topic/misc/cvjjgrwIHbU

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建一个返回 const 值的工厂构造函数 的相关文章

随机推荐