Search code examples
scalafunctional-programmingoption-typefor-comprehension

Scala for comprehension returns Option[List[T]]]; want List[Value]


I'm pretty new to Scala and am having some difficulty figuring out exactly how to extract form an Option

I have code that does:

getResult( name, age, id).map(response =>
  for {
    accounts <- response._id_list // response.account_id_list is an Option[String]
    ageList <- response.age_list // response.details is an Option[Details]
  } yield {
      accounts.split(" ").map(accountID =>  Account(
        accountID = accountID,
      ))
  }
)

This returns Option[List[Account]] but I just want to return a List[Account]. I know that the reason for this is because the for comprehension is really some syntactic sugar covering some flatMaps and maps but I can't figure out how to return the contents of the Option. I don't want to use Option.get because I've read that's terrible practice (as it essentially nullifies the whole point of the Option. So, how else can I do this?

Thanks in advance.


Solution

  • You can do a .getOrElse(List.empty)