Comparison between class and traits in Scala


Singleton Can create new instance Can have a constructor Can be inherited
Class No Yes Yes Yes
Abstract class No No Yes Yes
Trait No No No Yes
Object Yes No No No

Also a small trick: Since an object cannot be inherited, we need to create a trait (a trait make sure the object won’t have a constructor) with the common values and functions of the objects we wanted to create, then both object would inherit the trait, with one object expanding on the trait.

This construction can be applied to perform Enumeration inheritance in Scala (since Enums by convention are created as objects)

Leave a Reply

Your email address will not be published. Required fields are marked *