scala-logo-small

How Scala Even Does One Better Than The Adapter Pattern

UML Diagram of The Adapter Design Pattern
UML Diagram of The Adapter Design Pattern

The Adapter Pattern is a way to allow one object to be used as another object, usually by creating a wrapper class around the first object which implements the same method or methods. There are various versions. I suppose the correct OO way is to implement the same interface as the other object.

Scala has a powerful language feature called implicit classes that improves the pattern.

What the Adapter Pattern Looks Like
An example might be that you have two objects like this:

class Shuttle implements Spacecraft {

  void launch() {
    //implementation...
  }
}

class Rocket {

  void blastOff() {
    //implementation...
  }
}

And you then create the adapter for Rocket:

class RocketAdapter implements Spacecraft {
  private Rocket r;

  RocketAdapter(Rocket r) {
    this.r = r;
  }

  void launch() {
    r.blastOff();
  }
}

Simple enough concept. By having the adapter, you can (hopefully) limit the adaptation that occurs to the single time when the object initially enters your application (because you usually need an adapter when interfacing with other applications) and then go about your merry way the rest of the time. Then if anything ever changes about that external object, you just change the internals of the adapter and do not have to go and change every reference in your code.

Scala Implicit Keyword
In Scala, there are new ways to achieve the same goals. One of them is implicit classes. You just declare the adapter class with the word implicit. From that point on, as long as the implicit class is in scope, then you get a free, invisible wrapping from one object to the other.

implicit class RocketAdapter(val r: Rocket) {
  def launch = {
    r.blastOff
  }
}

With this declared, you don’t have to declare “new RocketAdapter(myRocket)” anywhere in your code. You can pretend like any Rocket object has a “launch” method without any ceremony. Just say “myRocket.launch()” and the language will take care of the rest.

But even better than that, the implicit keyword can be used on functions and parameters to allow surgical precision around what you want to do and how. If you are interested, you can (and should) read the chapter on implicit in Programming in Scala free online. This is an amazing and wonderful feature, and definitely one of the first things I found in Scala that made me want to leave Java forever.

Leave a Reply

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