2

有人可以帮我将其转换为 flatMap 或用于理解吗?我知道如何处理嵌套选项的更琐碎场景。

    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
      }
    }
4

4 回答 4

0

一个相对易读的直接转换是:

def significantOthers(nightClubPeoples : Option[Seq[Person]]): List[String] = {
  for {
    nightClubPeoples <- nightClubPeoples.toList
    person <- nightClubPeoples
  } yield person.significantOther.getOrElse("No Significant Other")
}

这里要注意的是,我们预先转换nightClubPeoples为列表,允许我们一直使用 for 理解。

但是,我怀疑您是否真的希望“没有重要的其他人”出现在您的列表signficantOtherNone。相反,它应该被忽略,这将给出更简单的:

def significantOthers(nightClubPeoples : Option[Seq[Person]]): List[String] = {
  for {
    nightClubPeoples <- nightClubPeoples.toList
    person <- nightClubPeoples
    significantOther <- person.significantOther
  } yield significantOther
}
于 2015-08-14T09:10:42.587 回答
0

干得好:

nightclubPeoples.toSeq.flatMap(_.map(_.signficantOther.getOrElse("No Signficant Other")))
于 2015-08-14T07:31:05.163 回答
0

我想我会使用折叠:

nightclubPeoples.fold[List[String]](Nil)(_.flatMap(_.signficantOther)(collection.breakOut))
于 2015-08-14T06:21:45.163 回答
0

我认为,Sascha Kolberg 的答案是一个更好的解决方案(只是省略 signficantOther 为空时的情况,即“No Signficant Other”不会出现在结果列表中),但是因为您要求“将其转换为 flatMap 或for-comprehension”,所以代码如下。

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-14T06:54:41.087 回答