Surprisingly, most programming languages don’t support the actual Delegation concept, which means dynamically extending an object and is supposed to be an alternative for static inheritance. The key difference to simple message forwarding (as in the GOF Delegation pattern) is, that within a delegatee method this (or self) always points to the delegator object. So, the delegatee is not an actual object but more a plug-in, the programming language Self consequently refers to it as Slots.

In Scala we can simulate this idea of delegation by using traits with a explicitly typed self reference. The type of the self reference must of course match the delegator class:

  trait Delegatee { this: Delegator =>

The only drawback is, that we can only access public members of the delegator here.

Below a real world example: We extend the java.awt.Rectangle class by some calculation methods. But without doing what extending usually means, which is creating a subclass:

object DelegationTest extends App {

  trait RectangleCalculations { this: java.awt.Rectangle =>
    def area = getWidth * getHeight

  val rect = new java.awt.Rectangle(10, 20) 
                    with RectangleCalculations


Leave a Reply

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