如果我在Map
val states = Seq(Ca, Wa, Ny)
val tuples: Seq[Any] = for(state <- states) yield {
val mapValue: Option[CustomCaseClass] = someMap.get(key)
mapValue match {
case Some(value) => {
//do some operations and return a tuple (String, String)
}
case _ => //do nothing, just continue the for loop
}
}
对于case _
我想什么都不做,简单地继续循环。但是使用上面的代码,我无法在toMap
上执行tuples
,我收到以下错误 -
Cannot prove that Any <:< (String, String)
这是因为它可能并不总是返回Seq [(String,String)]。我希望能够在tuples
上进行操作,我很简单地希望在未找到时跳过这个案例。任何指导都表示赞赏。
答案 0 :(得分:1)
假设以下设置:
sealed trait State
case object Ca extends State
case object Wa extends State
case object Ny extends State
val someMap = Map(Ca -> 1, Wa -> 2)
val states = Seq(Ca, Wa, Ny)
我们可以使用Option
作为同一for
理解中的另一个生成器:
val tuples: Seq[(String, String)] = for {
state <- states
value <- someMap.get(state)
} yield (state.toString, value.toString + "x")
Option
将被隐式转换为0到1个元素的集合,因此对于None
,将跳过以下所有代码,我们将获得此代码:
assert(tuples.toMap == Map("Ca" -> "1x", "Wa" -> "2x"))
您还可以在for
内插入任意支票,这样您就可以检查密钥存在并使用someMap(key)
,而不是someMap.get(key)
:
val tuples2: Seq[(String, String)] = for {
state <- states
if someMap.contains(state)
} yield (state.toString, someMap(state).toString + "x")
assert(tuples2.toMap == Map("Ca" -> "1x", "Wa" -> "2x"))
答案 1 :(得分:0)
由于case _
nothing
返回result
所以Seq[Any]
类型为map
,您可以过滤未找到元素,做val tuples: Seq[(String, String)] =
states.filter(i => someMap.get(i).nonEmpty).map(value => (myString, myString))
:
ffmpeg -i "rtmp://in/1" -i "rtmp://in/2" -filter_complex "overlay=70:50" -vcodec libx264 -preset ultrafast -f flv rtmp://out