Using Extractions

If you want to perform more powerful extractions and apply a series of pattern matching, you can use Scala extractors. In the next example, you’ll write an extractor to parse the details of a Task. First define a Task singleton class with an unapply method.

 object Task {
  def unapply(taskInfo : String) = {
  val parts = taskInfo.split("---")
  if(parts.size != 2) None else Some(parts(0), parts(1))
  }
 }

The unapply method expects the given string to contain one delimiter , and if the parameter conforms to that, unapply returns as a tuple the two parts before and after this delimiter. If the format does not conform, it returns a None, indicating a failure of extraction. The unapply method can signal a failure by returning ...

Get Functional Programming: A PragPub Anthology 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.