Thursday, February 13, 2014

Scala Traits Tutorial - Part 2 (Objects with Traits)

In my previous tutorial on Scala traits, I talked about the motivation behind traits and how they can be used to solve problems that crop-up in other languages, due to the lack of traits. It's obvious, from my previous tutorial, that traits can be used in the same way that interfaces are used in Java. But, traits can also contain default/concrete implementations, which gives us added benefit. In this tutorial, I'm going to give some examples of how you can instantiate classes and mix-in traits at the time the object is defined.

Using the same example as the first tutorial, let's assume we have a trait for a WorkVehicle, as follows.

trait WorkVehicle {
  def towWeight: Integer = {
    return 2500

This trait has a default/concrete implementation for the towWeight method. Next, let's consider a class for a PersonalVehicle that extends a base abstract class called Vehicle. Note that the class itself does not mix-in the WorkVehicle trait.

abstract class Vehicle

class PersonalVehicle extends Vehicle

Rather than creating a new class that mixes-in the WorkVehicle trait, we can do this at the time the class is created, like such.

val myWorkVehicle = new PersonalVehicle with WorkVehicle

This is a powerful feature. It allows us to mix-in traits for individual objects, only when needed, rather than doing it at the time that the class is designed. Very cool!

1 comment:

  1. Your Scala blog posts are easy to understand. I appreciate your work.

    Thank you