Search code examples
scala

Pattern matching in conjunciton with filter


Given the following code that I like to refactor, I'm only interested in lines matching the 1st pattern that occurs, is there a way of shortening this like let's say using it in conjunction with filter?

def processsHybridLinks(it: Iterator[String]): Unit =
    {
     for (line <- it) {
        val lineSplit = lineSplitAndFilter(line)
        lineSplit match {
          case Array(TaggedString(origin), TaggedString(linkName), TaggedString(target), ".") =>
            {
              println("trying to find pages " + origin + " and " + target)
              val originPageOpt = Page.findOne(MongoDBObject("name" -> (decodeUrl(origin))))
              val targetPageOpt = Page.findOne(MongoDBObject("name" -> (decodeUrl(target))))
              (originPageOpt, targetPageOpt) match {
                case (Some(origin), Some(target)) =>
                  createHybridLink(origin, linkName, target)
                  Logger.info(" creating Hybrid Link")
                case _ => Logger.info(" couldnt create Hybrid LInk")
              }

            }
          case _ =>
        }
      }
    }

Solution

  • Have a look at collect method. It allows you to use a PartialFunction[A,B] defined using an incomplete pattern match as a sort of combination map and filter:

    it.map(lineSplitAndFilter) collect {
      case Array(TaggedString(o), TaggedString(n), TaggedString(t), ".") =>
        (n, Page.findOne(...), Page.findOne(...))
    } foreach {
      case (n, Some(o), Some(t)) => ...
      case _ =>
    }