Traits

Scala Comments

In this blog post, you’ll learn about -

  1. Traits - Scala’s version of interfaces.
  2. Mix-ins - A design pattern using Traits.

Traits

Traits are a lot similar to Java’s interface. Consider the example below -

When you’re overriding an abstract method of a trait, you do not need to use the @override method.

If you need to inherit more than 1 trait, you can add it using the with keyword:

Unlike Java interfaces, Scala traits can have concrete implementations.

Mix-ins

Consider the example below -

So, now we can mix-in different Loggers at the time we create an object (this is an alternate way to have Dependency Injection in Scala).

Kaushik Rangadurai

Code. Learn. Explore

Share this post

Comments