Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Other differences you haven't mentioned: </p> <ul> <li>Trait classes do not have any independent existence:</li> </ul> <p>(<a href="http://programming-scala.labs.oreilly.com/ch04.html#ClassOrTrait" rel="noreferrer">Programming Scala</a>)</p> <blockquote> <p>If you find that a particular trait is used most often as a parent of other classes, so that the child classes behave as the parent trait, then consider defining the trait as a class instead, to make this logical relationship more clear.<br> (We said <em>behaves as</em>, rather than <em>is a</em>, because the former is the more precise definition of inheritance, based on the Liskov Substitution Principle - see [Martin2003], for example.)</p> </blockquote> <p><sup>[Martin2003]: Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice-Hall, 2003</sup></p> <ul> <li>mixins (<code>trait</code>) have no constructor parameters. </li> </ul> <p>Hence the <a href="http://programming-scala.labs.oreilly.com/ch04.html#ClassOrTrait" rel="noreferrer">advice, still from Programming Scala</a>:</p> <blockquote> <p>Avoid concrete fields in traits that can’t be initialized to suitable default values.<br> Use abstract fields instead <strong>or convert the trait to a class with a constructor</strong>.<br> Of course, stateless traits don’t have any issues with initialization.</p> <p>It’s a general principle of <strong>good object-oriented design that an instance should always be in a known valid state, starting from the moment the construction process finishes</strong>.</p> </blockquote> <p>That last part, regarding the <strong><em>initial</em> state</strong> of an object, has often helped decide between class (and class composition) and trait (and mixins) for a given concept.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload