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

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

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