本文介绍了为什么不能以任何方式修改常量列表时不能在字符串文字中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main() {
  const list = [1, 2, 3];
  const string = 'This is a $list'; // Error
}

当我不能为 list 分配新值并修改其任何元素时,为什么不能在字符串文字中使用 list ?

When I can't assign list a new value and modify any of its elements, why can't I then use the list in my string literal?

推荐答案

Dart的概念并不在于可以在编译时评估方法调用(与C ++中的 constexpr 相比)).因此,Dart无法保证在 const 对象上调用方法将返回另一个 const 对象,并且该对象包括对 .toString()的隐式调用.做字符串插值.

Dart doesn't have a concept of saying that a method call can be evaluated at compilation time (in contrast to constexpr in C++). Therefore Dart cannot guarantee that calling a method on a const object returns another const object, and that includes the implicit call to .toString() when doing string interpolation.

例如,这是完全合法的:

For example, this is perfectly legal:

import 'dart:math';

final random = Random();

class Foo {
  const Foo();

  // Returns a string that is clearly not a compile-time constant.
  @override
  String toString() => random.nextInt(100).toString();
}

void main() {
  const foo = Foo();
  print('$foo');

  const list = [foo, foo, foo];
  print('$list');
}

请注意,这不适用于某些内置类型(例如null,数字,字符串和布尔类型)的 .toString()实现,因为已知它们会产生常量值和因为Dart不允许从这些类型创建派生类,所以不能像上面的示例那样重写它们来进行欺骗.

Note that this doesn't apply to .toString() implementations for some built-in types (e.g. null, numeric, string, and boolean types) since they are known to produce constant values and because Dart does not allow creating derived classes from those types, so they cannot be overridden to do shenanigans like the above example.

这篇关于为什么不能以任何方式修改常量列表时不能在字符串文字中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:37