dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.22k stars 1.57k forks source link

Allow references to classes in constant string expressions #32715

Open yjbanov opened 6 years ago

yjbanov commented 6 years ago

The following code should be valid Dart, but instead it results in a compiler error:

class Foo {
  const Foo() : className = '$Foo';
  //                         ^
  //                         error here

  final String className;
}

Error: "In constant expressions, operands of this operator must be of type 'bool', 'num', 'String' or 'null'."

zoechi commented 6 years ago

That would be nice if this worked, but doesn't this require a call to toString()? What about String get className => runtimeType.toString();

yjbanov commented 6 years ago

That would be nice if this worked, but doesn't this require a call to toString()?

The following code works, and requires the same level of compile-time toString() support:

class Foo {
  const Foo() : className = '${5}';
  final String className;
}

What about String get className => runtimeType.toString();

The code I provided is only a minimal example that demonstrates the problem. It has little to do with what I want to use it for. In my case, I am extending a class with a const constructor that takes a string intended for describing my object. I'd like to be able to create const instances of my class and be able to use the class' name in the description. Here's a more complete example:

abstract Describable {
  const Describable(this.description);
  final String description;
}

class Foo extends Describable {
  const Foo() : super('$Foo that does fooey things');
}

Certainly I could use 'Foo' instead of '$Foo' but I'd loose analysis benefits. For example, if I refactor the code and rename class Foo to something else, I will likely forget to update the string. But '$Foo' would catch it (and in the case of an IDE, rename it automatically).

matanlurey commented 6 years ago

How would this work with obsfucation?

yjbanov commented 6 years ago

Since it's a compile-time constant it can be computed prior to obfuscation.