有没有人能帮我把这个转换成flatMap或者for- Can?我知道如何处理嵌套选项的更多微不足道的场景。
case class Person(name: String, signficantOther: Option[String])
val nightclubPeoples : Option[Seq[Person]] = ???
def significantOthers(nightClubPeoples : Option[Seq[Person]]) : List[String] = {
nightclubPeoples match {
case Some(x) => x map { y : Person =>
y.significantOther match {
case Some(z) => z
case None => "No Signficant Other"
}
}.toList
case None => Nil
}
}发布于 2015-08-14 14:21:45
我想我会用一个折叠键:
nightclubPeoples.fold[List[String]](Nil)(_.flatMap(_.signficantOther)(collection.breakOut))发布于 2015-08-14 14:54:41
Sascha Kolberg的答案是,正如我所认为的,对于你的问题,一个更好的解决方案(只是省略了signficantOther为空的情况,即"No Signficant Other“不会出现在结果列表中),然而,因为你要求”将其转换为flatMap或用于理解“,所以代码如下所示。
case class Person(name: String, signficantOther: Option[String])
val nightClubPeopleOpt : Option[Seq[Person]] = Some(Person("name", Some("1")) :: Person("name1", None) :: Nil)
def significantOthers(nightClubPeopleOpt : Option[Seq[Person]]) = {
for {
nightClubPeople <- nightClubPeopleOpt
} yield {
// scenario 1
// if signficantOther is empty, then it should be ignored
// Answer -> List(1)
nightClubPeople.flatMap(_.signficantOther).toList
// scenario 2
// if signficantOther is empty, then we use the default "No Signficant Other"
// Answer -> List(1, No Signficant Other)
nightClubPeople.map { nightClubPerson =>
nightClubPerson.signficantOther.getOrElse("No Signficant Other")
}.toList
}
}.getOrElse(Nil)
println(significantOthers(nightClubPeopleOpt))发布于 2015-08-14 15:31:05
这就是了:
nightclubPeoples.toSeq.flatMap(_.map(_.signficantOther.getOrElse("No Signficant Other")))https://stackoverflow.com/questions/32003391
复制相似问题