Scala Class Examples: Trait Keyword2 min read

Use a class and create it with the new-keyword. A trait is used to extend a class.Classes. A Game class has fields and methods. It has the current score. It has players. And it can take turns with a play method.With traits, and the trait keyword, we can extend features of our classes. A Game might be extended to adjust the rules. It might add features or options.First example. Here we introduce a Test class. On this class we find a method print(). This writes a greeting to the screen. We create a new instance of Test with the new-keyword.


Traits. A trait is used to extend a class. We can compose a class by adding those traits to its definition. This allows us to combine many capabilities in a class.

Here: We have a Page class, and an Image and Paragraphs traits. A trait is defined in a similar way as a class, but uses the trait keyword.

ComplexPage: This class is based on the Page class, but also adds the Image and Paragraphs traits. It contains all three methods.

Finally: We create a ComplexPage instance and call print, printImages and printParagraphs from the Page class and the two traits.



Leave a Comment