性状混合的限制
我想要拥有只能混合指定特征的类:
class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral
Scala 中有一种方法可以做到这一点吗?
UPD:
trait Law
trait Lawful extends Law
trait LNeutral extends Law
trait Chaotic extends Law
trait Moral
trait Good extends Moral
trait Neutral extends Moral
trait Evil extends Moral
class Hero .........
class Homer extends Hero with Chaotic with Good
我想以一种限制客户端程序员混合特定特征的方式定义一个 Hero
类(Lawful
/LNeutral
/如果他扩展了
和Hero
类,则为混乱善良
/中立
/邪恶
)。我想找到一些其他的可能性来限制/限制像这样的客户端代码。
I want to have classes that can mix only specified traits:
class Peter extends Human with Lawful with Evil
class Mag extends Elf with Chaotic with Neutral
Is in Scala a way to do this?
UPD:
trait Law
trait Lawful extends Law
trait LNeutral extends Law
trait Chaotic extends Law
trait Moral
trait Good extends Moral
trait Neutral extends Moral
trait Evil extends Moral
class Hero .........
class Homer extends Hero with Chaotic with Good
I want to define a Hero
class in a way that constrains the client programmer to mix specific traits (Lawful
/LNeutral
/Chaotic
and Good
/Neutral
/Evil
) if he extends the Hero
class. And I want to find some other possibilities to restrict/constrain client code like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
艰难的。试试这个:
如果您想要求必须扩展 Law 类型,那么您需要在某些基类或特征中使用 self 类型:
并且还有一些进一步的调整以确保进一步的类型安全。最终结果可能如下所示:
Tough. Try this:
If you want to make it a requirement that a Law type must be extended, then you need to to use self types in some base class or trait:
And there are a few further tweaks to ensure further type safety. The final result might look like this:
也许您正在寻找限制自我类型声明。例如:
Perhaps you're looking for restricting self-type declarations. E.g.:
您可以检查
Human
和/或Elf
的构造函数是否具有允许的特征的实例:You can check in the constructor of
Human
and/orElf
if its an instance of the allowed traits: