0

I have an issue related to the new instantiate to bound rule in Dart 1.22.0. I have a BaseModel class that takes a parameterized type called ParentType that itself extends BaseModel.

Not all BaseModels have a specific ParentType, and if I instantiate BaseModel as the ParentType, then I get infinite rule breaking.

Here's an example:

abstract class BaseModel<ParentType extends BaseModel> {
    ParentType parentModel
}

class ParentModel extends BaseModel<BaseModel<...>> {}

class ChildModel extends BaseModel<ParentModel> {}

I’m going to be ignoring the rule for now as this issue hasn't seemed to have any impact on development.

Sam B
  • 187
  • 12

2 Answers2

2

Depends a bit on what you want to accomplish, but assuming that you want ParentModel to be usable as any kind of BaseModel (where the parentModel field will always be null), then this may be what you want:

abstract class BaseModel<ParentType extends BaseModel<ParentType>> {
  ParentType parentModel;
}

class ParentModel extends BaseModel<Null> {}

class ChildModel extends BaseModel<ParentModel> {}

If not, I would need to know more about what the constraints and goals of your problem are.

  • This satisfies the analyzer for the basic example, but it breaks where I have more complex inheritance. `class ParentModel extends ChildModel` `class ChildModel extends BaseModel` My codebase is too large and complex to make all of these typing changes, and I don't see the benefit. I am resigned to ignoring the rule. I've struggled with strong mode in the past, which was the impetus to implement this pattern to begin with. Before this, I was overriding field types, which to me seems like a preferred solution. – Sam B Feb 17 '17 at 23:02
0

This might do what you want:

abstract class BaseModel<ParentType extends BaseModel<Null>>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567