O'Reilly logo

Scala Design Patterns - Second Edition by Ivan Nikolov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The visitor design pattern the Scala way

As with many other design patterns we saw earlier, the visitor design pattern could be represented in a way that is less verbose and closer to Scala. The way things can be done in order to implement a visitor in Scala is the same as the strategy design pattern—pass functions to the accept method. Moreover, we can also use pattern matching instead of having multiple different visit methods in the Visitor trait.

In this subsection, we will show both the improvement steps. Let's start with the latter.

First of all, we need to make the model classes case classes in order to be able to use them in pattern matching:

abstract class Element(text: String) {  def accept(visitor: Visitor)}case class Title(text: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required