Duck typing example

Everything becomes clearer with an example. Let's imagine that we want to have a method which can take a parser and print every word that the parser detects. Our parsers will have a method with the following signature:

def parse(sentence: String): Array[String]

A good way of doing this would be to have a common interface and make all the parsers implement it. However, let's set a condition that we cannot do this. The parsers could be coming from two different libraries where we cannot modify or connect in any way.

We have defined two different parser implementations for this example. The first one is as follows:

import java.util.StringTokenizerclass SentenceParserTokenize {  def parse(sentence: String): Array[String] = ...

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.