[英]Optional tuples to Map in Scala
If I have a List of tuples, I can convert to a map with toMap
: 如果我有一个元组列表,则可以使用
toMap
转换为地图:
val x = (3 -> 3)
List(x).toMap
and I get 我得到
scala.collection.immutable.Map[Int,Int] = Map(3 -> 3)
If I have a List of Optional and try the same I would get an error: 如果我有一个可选列表并尝试使用相同列表,则会收到错误消息:
val x = Some(3 -> 3)
val y = None
List(x, y).toMap
<console>:15: error: Cannot prove that Some[(Int, Int)] <:< (T, U).
I want to get the same result. 我想得到相同的结果。 Is it possible?
可能吗?
You can use flatten
on the List
to remove the None
s: 您可以在
List
上使用flatten
删除None
:
val x = Some(3 -> 3)
val y = None
List(x, y).flatten.toMap
> scala.collection.immutable.Map[Int,Int] = Map(3 -> 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.