我有一个类似这样的代码段:
def test() : Seq[Int] =
List("A", "B", "C") collect {
case "A" => 1
case "B" => 2
//case _ => println(_)
}
现在,我想在输出上打印特定值(仅用于调试),而不向生成的集合添加任何元素。如果我取消注释行的注释,Scala会将表达式的值推断为Seq[Any]
,这是完全可以理解的。
有人知道怎么做吗?提前感谢!
我有一个类似这样的代码段:
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 }
}
}
})
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 ...
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, ...
I m going to work on comparing around 300 binary files using Scala, bytes-by-bytes, 4MB each. However, judging from what I ve already done, processing 15 files at the same time using java....
The scala type Nothing represents (as I understand it) the bottom of the type hierarchy, also denoted by the symbol ⊥. That is, Nothing is a sub-type of any given type. The requirement for a Nothing ...
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 ...
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 ...
I am trying to use Scala s capabilty of running a class with either JUnit or ScalaTest. I took the example given for FeatureSpec and combined it with the example using JUnitSuite. I am having a ...
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 ...