Reputation: 1
I probably just simply overlooked something, but I have a simple class tree where the superclass has a simple toString() method. When calling it from the derived class instance, I get a crash in VS Code:
class Item {
String status = "";
String name = "";
Item();
String toString() {
return "$this.name ($this.status)";
}
}
class MiscItem extends Item {}
class FoodItem extends Item {}
class DrinkItem extends Item {}
DrinkItem coke1 = new DrinkItem();
print(coke1.toString());
Then it drops dead with:
===== CRASH =====
ExceptionCode=-1073741819, ExceptionFlags=0, ExceptionAddress=00007FF7E9F498FE
version=2.16.1 (stable) (Tue Feb 8 12:02:33 2022 +0100) on "windows_x64"
pid=14904, thread=14540, isolate_group=main(000001FED427C020), isolate=main(000001FED4295B80)
isolate_instructions=7ff7e9e15450, vm_instructions=7ff7e9e15460
Stack dump aborted because GetAndValidateThreadStackBounds failed.
Exited (3221226505)
What did I mess up here? AFAIK DrinkItem should inherit both the superclass' toString() method and the status and name properties. Still, calling DrinkItem's toString() crashes.
Upvotes: 0
Views: 170
Reputation: 8383
You need curly braces in your string interpolation:
String toString() {
return "${this.name} (${this.status});
}
Otherwise, it will be equivalent to "${this}.name (${this}.status)"
and hence recursively invoke your toString()
method.
By the way, in Dart, you don't have to use this
inside the class. You can simplify your toString()
method to:
String toString() {
return "$name ($status);
}
Upvotes: 1