A code example

Here, we will show the code of our interpreter application step by step. We currently have some limitations such as only supporting integers, not having a good error reporting mechanism, and only having three operations, but it is easy to add new ones. You could try and build on top of what we already have.

First of all, let's see the base Expression trait:

trait Expression {  def interpret(): Int}

It is really simple and contains one method that other expressions will have to implement. The terminal expression, which is our Number class, looks like the following:

class Number(n: Int) extends Expression {  override def interpret(): Int = n}

It doesn't do anything special—just returns the number it carries when interpret is called. ...

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.