Search code examples
regexscalapartialfunction

Scala regex + partial function unapply performance


Assume that I have a code like:

val pf: PartialFunction[String, Unit] =
  "string" match { case regex(g1, g2, _*) =>
    function(g1, g2)
  }

pf has methods isDefinedAt and apply. Will the regex search be evaluated once, in isDefinedAt point, or the job will be done twice?

If once, how args g1, g2 get passed to apply method?


Solution

  • The regex will be evaluated once. The work is done in the extractor, Regex.unapplySeq. The extractor's return type is Option[List[String]] so it knows whether the regex was a match (either Some or None) and the captured groups (the List[String]) all in one bundle.