3

我有一个类似这样的代码段:

def test() : Seq[Int] = 
  List("A", "B", "C") collect {
    case "A" => 1
    case "B" => 2
    //case _ => println(_)
  }

现在我想在输出上打印特定值(仅用于调试),而不向结果集合添加任何元素。如果我取消注释注释行,Scala 将表达式的值推断为Seq[Any],这是完全可以理解的。

有人有任何提示如何做到这一点吗?提前致谢!

4

3 回答 3

9
def skipped: Nothing = throw new Exception("Oops, not skipped after all!")

List("A", "B", "C") collect {
  case "A" => 1
  case "B" => 2
  case x if { println(x); false } => skipped
}

object PrintSkip {
  def unapply(a: Any): Option[Any] = {
    println(a)
    None
  }
}

List(Some("A"), None, Some("C")) collect {
  case Some("A") => 1
  case None => 2
  case Some(PrintSkip(_)) => skipped
}
于 2012-05-27T17:51:02.857 回答
8

flatMap

List("A", "B", "C") flatMap {
    case "A" => List(1)
    case "B" => List(2)
    case x => println(x); Nil
}

collect/flatten

List("A", "B", "C").collect {
    case "A" => Some(1)
    case "B" => Some(2)
    case x => println(x); None
}.flatten
于 2012-05-27T17:19:38.667 回答
3

使用 collect,无需将内容包装在 Option 中。

List("A", "B", "C").collect(new PartialFunction[String, Int] {
  def apply(s:String):Int = s match {
    case "A" => 1
    case "B" => 2
  }

  def isDefinedAt(s:String) = {
    try {
      apply(s)
      true
    } catch {
      case e:MatchError => { println(s); false }
    }

  }
})
于 2012-05-27T17:42:46.527 回答