Extractors and Regular Expressions

Scala’s powerful pattern matching does not stop with built-in matching facilities. You can create custom matching using extractors and, there too, Scala gives us a few different alternatives.

Matching Using Extractors

You can take pattern matching to the next level by matching arbitrary patterns using Scala extractors. As the name indicates, an extractor will extract matching parts from the input. Suppose we’re writing a service that will process stock-related input. The first task on hand is for us to receive a stock symbol and return the price for that stock. Here’s an example of calls we can expect:

 
StockService process ​"GOOG"
 
StockService process ​"IBM"
 
StockService process ​"ERR"

The process method ...

Get Pragmatic Scala 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.