John Doe
John Doe

Reputation: 281

How to unwrap optional tuple of options to tuple of options in Scala?

I have a list of Person and want to retrieve a person by its id

val person = personL.find(_.id.equals(tempId))

After that, I want to get as a tuple the first and last element of a list which is an attribute of Person.

val marks: Option[(Option[String], Option[String])] = person.map { p =>
              val marks = p.school.marks
              (marks.headOption.map(_.midtermMark), marks.lastOption.map(_.finalMark))
}

This work's fine but now I want to transform the Option[(Option[String], Option[String])] to a simple (Option[String], Option[String]). Is it somehow possible to do this on-the-fly by using the previous map?

Upvotes: 2

Views: 1493

Answers (2)

Dima
Dima

Reputation: 40508

You are, probably, looking for fold:

personL
 .collectFirst {
    case Person(`tempId`, _, .., school) => school.marks
 }.fold[Option[String], Option[String]](None -> None) { marks => 
    marks.headOption.map(_.midtermMark) -> marks.lastOption.map(_.finalMark) 
 }

Upvotes: 0

dk14
dk14

Reputation: 22374

I suppose:

person.map{...}.getOrElse((None, None))

(None, None) is a default value here in case if your option of tuple is empty

Upvotes: 1

Related Questions