Is it possible to print values during collect without modifying return type?

202 Views Asked by At

I have a code segment something like this:

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

Now I would like to print specific values (just for debugging) on the output without adding any elements to the resulting collection. If I uncomment the commented line, Scala infers the value of the expression to Seq[Any], which is completely understandable.

Anybody got any hints how to do this? Thanks in advance!

3

There are 3 best solutions below

0
On BEST ANSWER

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
On

With collect, no need for wrapping things in an 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 }
    }

  }
})
2
On
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
}