Scala Language String Interpolation String interpolators as extractors


Example

It is also possible to use Scala's string interpolation feature to create elaborate extractors (pattern matchers), as perhaps most famously employed in the quasiquotes API of Scala macros.

Given that n"p0${i0}p1" desugars to new StringContext("p0", "p1").n(i0), it is perhaps unsurprising that extractor functionality is enabled by providing an implicit conversion from StringContext to a class with property n of a type defining an unapply or unapplySeq method.

As an example, consider the following extractor which extracts path segments by constructing a regular expression from the StringContext parts. We can then delegate most of the heavy lifting to the unapplySeq method provided by the resulting scala.util.matching.Regex:

implicit class PathExtractor(sc: StringContext) {
  object path {
    def unapplySeq(str: String): Option[Seq[String]] =
      sc.parts.map(Regex.quote).mkString("^", "([^/]+)", "$").r.unapplySeq(str)      
  }
}

"/documentation/scala/1629/string-interpolation" match {
  case path"/documentation/${topic}/${id}/${_}" => println(s"$topic, $id")
  case _ => ???
}

Note that the path object could also define an apply method in order to behave as a regular interpolator as well.