从scala中的可选项创建列表的最佳方式是什么



我有一段代码,它包含一个带有少数Option字段的case类(ContentBlock)。如果这些字段不是"无",我想创建一个对象列表(描述)。。。所以我制作了以下代码,它很有效,但我强烈怀疑它很糟糕。首先,匹配不考虑"无",它只是将任何带有"无"的字段丢弃在地板上,编译器正确地"告诉"我这很糟糕。

做这样的事情最好的模式是什么?这是代码。。。

implicit def ContentBlockToDescriptionList(a: ContentBlock): List[Description] = {
  List[Description](
    a.instructions match {
      case Some(x) => new Description("Instructions", x)
    },
    a.terms_and_conditions match {
      case Some(x) => new Description("Terms and Conditions", x)
    },
    a.cancellation_addendum match {
      case Some(x) => new Description("Cancellation Addendum", x)
    }
  )
}

如果每个可选字段的底层类型相同,则可以编写:

List(("Instructions", a.instructions),
     ("Terms and Conditions", a.terms_and_conditions),
     ("Cancellation Addendum", a.cancellation_addendum)
).collect {
  case (desc, Some(x)) => new Description(desc, x)
}

顺便说一下,原始代码不会"将None值掉到地板上";它应该使用非详尽匹配警告进行编译,并且在运行时将使用MatchError失败。

您可以这样简化它:

List(
  a.instructions map (new Description("Instructions", _)),
  a.terms_and_conditions map (new Description("Terms and Conditions", _)),
  a.cancellation_addendum map (new Description("Cancellation Addendum", _))
).flatten

也许您可以使用flatten。像这样:

implicit def ContentBlockToDescriptionList(a: ContentBlock): List[Description] =
  List[Option[Description]](
    a.instructions.map(new Description("Instructions", _)),
    a.terms_and_conditions.map(new Description("Terms and Conditions", _)),
    a.cancellation_addendum.map(new Description("Cancellation Addendum", _))
  ).flatten

最新更新