Smartly deal with Option[T] in Scala

只谈情不闲聊 提交于 2020-01-24 04:11:36

问题


I am developing some code using Scala and I am trying to smartly resolve a basic transformation between collections that contains some Option[T].

Let's say that we have the following list

val list: List[(A, Option[B])] = // Initialization stuff

and we want to apply a transformation to list to obtain the following list

val transformed: List[(B, A)]

for all Option[B]s that evaluate to Some[B]. The best way I found to do this is to apply the following chain of transformations:

val transformed = 
  list.filter(_.isDefined)
      .map { case (a, Some(b)) => (b, a) }

However I feel that I am missing something. Which is the best way to deal with Option[T]s?


回答1:


You can use collect:

val transformed = list.collect {
  case (a, Some(b)) => (b, a)
}

Collect, as defined in the docs:

Builds a new collection by applying a partial function to all elements of this list on which the function is defined.

Meaning, it yields a result only for elements which match any of the cases defined in your partial function. I like to think of it as a combined filter and map.



来源:https://stackoverflow.com/questions/35302647/smartly-deal-with-optiont-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!