Skip to content

Trait

wikipedia Trait (computer programming)

In computer programming, a trait is a concept used in object-oriented programming, which represents a set of methods that can be used to extend the functionality of a class.

Characteristics

Traits both provide a set of methods that implement behaviour to a class, and require that the class implement a set of methods that parameterize the provided behaviour.

For inter-object communication, traits are somewhat between an object-oriented protocol (interface) and a mixin. An interface may define one or more behaviors via method signatures, while a trait defines behaviors via full method definitions: i.e., it includes the body of the methods. In contrast, mixins include full method definitions and may also carry state through member variable, while traits usually don't.

NOTE: this paragraph summarize the difference between interface,trait and mixin.

Hence an object defined as a trait is created as the composition of methods, which can be used by other classes without requiring multiple inheritance. In case of a naming collision, when more than one trait to be used by a class has a method with the same name, the programmer must explicitly disambiguate which one of those methods will be used in the class; thus manually solving the diamond problem of multiple inheritance. This is different from other composition methods in object-oriented programming, where conflicting names are automatically resolved by scoping rules.

NOTE: trait can be used by other classes without requiring multiple inheritance whereas mixin need

Whereas(然而) mixins can be composed only using the inheritance operation, traits offer a much wider selection of operations, including:[3][4]

  • symmetric sum: an operation that merges two disjoint traits to create a new trait
  • override (or asymmetric sum): an operation that forms a new trait by adding methods to an existing trait, possibly overriding some of its methods
  • alias: an operation that creates a new trait by adding a new name for an existing method
  • exclusion: an operation that forms a new trait by removing a method from an existing trait. (Combining this with the alias operation yields a shallow rename operation).

Traits are composed in the following ways:

  • Trait composition is commutative; the ordering of adding traits does not matter. For example, given trait S = A + B, then trait T = B + A is the same as S.
  • Conflicting methods are excluded from the composition.
  • Nested traits are equivalent to flattened traits; the composition hierarchy does not affect the traits behaviour. For example, given trait S = A + X, where X = B + C, then trait T = A + B + C is the same as S.[1]

Supported languages