0

给定以下我想重构的代码-我只对匹配出现的第一个模式的行感兴趣,有没有办法缩短它,比如将它与过滤器结合使用?

最诚挚的问候,

斯特凡

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 _ =>
        }
      }
    }
4

1 回答 1

2

看看collect方法。它允许您使用PartialFunction[A,B]定义的使用不完整的模式匹配作为一种组合mapfilter

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 _ =>
}
于 2013-10-10T14:29:57.490 回答