【发布时间】:2019-10-09 11:46:57
【问题描述】:
我想强制一个类User 来实现抽象类Base 中的一个静态成员。这可能吗,还是我错误地使用了抽象继承范式?
如果没有继承,User 可以简单地实现自己的静态成员而不覆盖 Base,但我希望我的 linter 在 Class 未实现某些静态成员时发出警告。
什么有效(不强制接口)
我们可以在Base和User中隐式使用相同的接口。
abstract class Base {
// This member could simply be removed and the snippet would still compile.
static final String routeName = '/base';
}
class User extends Base {
static final String routeName = '/base/user';
}
如果我们要创建一个新的类Person 来扩展Base,我们没有具体的实现要求。理想情况下,我想强制 Person 拥有一个静态成员 routeName。
class Person extends Base {
// No warning about a missing static member 'routeName'.
}
idea 示例(不编译)
Base 将包含一个未实现的静态成员 (routeName)。
除非我们指定 routeName(例如 routeName = '/base'),否则此 sn-p 不会编译。
abstract class Base {
// IDE Error: The final variable 'routeName' must be initialized.
static final String routeName;
}
实现Base 的User 将覆盖或实现静态成员。
sn-p 报告警告,除非我们删除错误放置的@override。
class User extends Base {
// IDE Warning: Field doesn't override an inherited getter or setter.
@override
static final String routeName = '/base/user';
}
我希望 IDE 为 Person 类抛出错误,因为它没有实现静态成员 routeName。
class Person extends Base {
// Expected IDE Error: The static final variable 'routeName' must be initialized.
}
在我看来,这类似于 how Java does it,但我不熟悉 Java 细节。
【问题讨论】:
-
您愿意接受其他解决方案吗?这不可能如您所愿,但还有其他非常方便的方法可以实现。
-
欢迎对静态成员强制执行这种类行为的任何其他解决方案。我的主要目标是捕获有异味或不完整的类(最好使用静态代码分析或 IDE 中的 linting)。
-
期待完全相同的功能/解决方案/绕过
-
我一直在使用 getter 来实现类似的东西。结果是一个易于实现的类,但 getter 仍然需要一个本地定义的常量来实现编译时间的方法。
标签: inheritance dart interface