我有一个像这样的代码段:
def test() : Seq[Int] =
List("A", "B", "C") collect {
case "A" => 1
case "B" => 2
//case _ => println(_)
}
现在我想在输出上打印特定值(仅用于调试),而不向结果集合添加任何元素。如果我取消注释注释行,Scala会将表达式的值推断为Seq[Any]
,这是完全可以理解的。
任何人都有任何提示如何做到这一点?提前谢谢!
答案 0 :(得分: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
}
答案 1 :(得分: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
答案 2 :(得分: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 }
}
}
})