O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

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

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