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: ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.