Reputation: 281
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
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
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