Object-oriented – What’s the difference between a Mixin and a Trait

mixinsobject-orientedPHPscalatrait

From what I can tell from Scala and Hack-

Mixins:

  • Can have state (ie. instance properties)
  • Can only provide concrete methods
  • Can have constructors, that are called in the same order that their classes were mixed in
  • If A mixes in B and C, A instanceof B == false and A instanceof C == false

Traits:

  • Can only provide methods, not state
  • Can declare abstract methods, that a consumer must implement
  • Cannot have constructors
  • If A implements traits B and C, A instanceof B == false and A instanceof C == false

Is this correct or am I missing anything ? Are these definitions accurate for any OO language or just for the above mentioned ones ?

Best Answer

PHP does not have concept of mixins, however it has traits which look like mix of traits and mixins from hack/scala:

  • Can define properties.
  • Can define constructors.
  • Can define abstract methods.
  • Does not support inheritance.
  • Traits are not types.

Are these definitions accurate for any OO language or just for the above mentioned ones ?

I don't think that there is even a single thing that will work in the same way in all OO languages. Even some basics like inheritance and interfaces have some variations, not mention more blurred constructs like traits/mixins.