English 中文(简体)
是否可以在不修改返回类型的情况下在收集过程中打印值?
原标题:Is it possible to print values during collect without modifying return type?

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

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

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

有人知道怎么做吗?提前感谢!

最佳回答

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
问题回答
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
}

有了收藏,就不需要把东西包装在选项中。

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 }
    }

  }
})




相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签