Question

I have code that takes in a case class (ContentBlock) with a handful of Option fields. I want to create a list of objects (Description) built from those fields IF they are not "None" ... so I've made the following code, which works, but I strongly suspect is terrible. First, the match doesn't account for "None," it just drops any field with None on the floor, which the compiler properly tells me is bad.

What's the best pattern for doing something like this? Here's the code...

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)
    }
  )
}
Was it helpful?

Solution

If the underlying type of each optional field is the same, you could write:

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

By the way, the original code won't "drop the None values on the floor"; it should be compiling with a non-exhaustive match warning, and will fail at runtime with a MatchError.

OTHER TIPS

You can simplify it like this:

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

Maybe you can use flatten. like this:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top