Montenegrodr
Montenegrodr

Reputation: 1636

How convert from Option[Seq[A]] to List[A] in Scala

I have this class:

case class MyClass(field1: Option[Seq[String]],
                   field2: Option[Seq[String]],
                   field3: Option[Seq[String]])

and I need to translate/parse those fields into another structure of type List[String] .

Already tried with map.(x => x.toString()) and flatten, but no donuts so far.

This snippet:

Option[Seq[String]].toList.flatten.distinct gives me List[Any].

Upvotes: 2

Views: 6024

Answers (2)

Don Branson
Don Branson

Reputation: 13709

You might find similar statements in various places such as this one from Idiomatic Scala: Your Options Do Not Match:

The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use map, flatMap, filter, or foreach […] A less-idiomatic way to use scala.Option values is via pattern matching

That page offers an example of fold which might be used like this to give a List[String]:

field.fold(List[String]())(_.toList)

As suggested by @Evgeny, this also results in a List[String]:

field.toList.flatten.distinct

Upvotes: 2

Andrei T.
Andrei T.

Reputation: 2480

Hmm, I think you could do it using getOrElse (and toList if you're not happy with a Seq):

// Seq[String]
field.getOrElse(List.empty)

// List[String]
field.getOrElse(List.empty).toList

I'm assuming you could use an empty List if a field is None. Hope that helps!

Upvotes: 4

Related Questions