1
votes

Specific case that I have encountered. How to handle effectively Scala Option of Collections of specific type?

As mentioned in one of the answers, using Option of Collection is not optimal and it's better to represent the absence of values with empty collection. But, this signature is force of me by a wacky external service.

So, and example. I have:

val myData = Option[Seq[MyObj]]

case class MyObj(name: String)

I want to map myData to some other type which is an Seq of NewObj.

val newData: Seq[NewObj] = myData.XXX

What is the best practice to map myData to different object?

3

3 Answers

3
votes

I would first say that you should rethink the need for an Option of a collection. It is typically preferred to simply represent the absence of values with an empty collection.

But if you really need the Option, then you can do this assuming transform is of type (MyObj) => MyNewObj:

val nyNewData: Option[Seq[MyNewObj]] = myData.map(_.map(transform))
2
votes

If Option[Seq[Obj]] is given, I'd getOrElse the option with an empty sequeunce:

object NewTest {
  case class MyObj(name: String)
  case class OtherObj(name: String, hash: Int)

  def main(args: Array[String]): Unit = {
    val myData: Option[Seq[MyObj]] = Some(Seq(MyObj("a")))
    val transformed: Seq[OtherObj] = 
      myData
        .getOrElse(Seq.empty[MyObj])
        .map(obj => OtherObj(obj.name, obj.name.hashCode))
}
0
votes
myData.map(list => list.map(myObj => doThing(myObj)))
// Option[Seq[NewThing]]