user887222
user887222

Reputation:

can an interface enforce which traits a class must use?

My question is simply, can an interface enforce which traits a class must use?

the reason I ask is that I imagine a namespaced set of interfaces that referred to traits with the same name that existed with different implementations in different namespaces to create complex but generic operations throughout an application. -makes sense?

Upvotes: 3

Views: 114

Answers (2)

madfriend
madfriend

Reputation: 2430

No, you can't do that.

Interfaces only require a class to implement methods. It knows nothing about whether such packed implementations (traits) exist.

Upvotes: 1

Matthew
Matthew

Reputation: 48284

Traits are essentially copy-and-pasted code, and shouldn't be thought of in terms of interfaces or inheritance. Interfaces cannot enforce traits. However, a trait could serve as an implementation of an interface.

You can have a trait that is composed of other traits. Or you can have an abstract base class that uses several traits. Both of those solutions may be something that you are looking for.

Upvotes: 1

Related Questions