I have the following code:
for {
totalUsers = currentUsers.map { u =>
newUsersMap.get(u.username.get).map { t =>
FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)
}
}
} yield {
totalUsers
}
This is returning a Seq[Option[FullUser]]
when what I want is a Seq[FullUser]
- i.e. if that call to u.username.get
returns None, then just ignore it. How do I do this?
Consider flatmapping.
val totalUsers = currentUsers.flatMap { u =>
newUsersMap.get(u.username.get).map { t =>
FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)
}
}
For some explanation how Seq
, Option
, and flatMap
work together, see for example this blog post.
Just try for comprehension
for {
user <- currentUsers
username <- user.username.toList //you need to convert to seq type to prevent ambiguous option seq mix problems.
t <- newUserMap.get(username).toList
} yield FullUser(t.username, u.firstName, u.lastName, u.batch, t.description)
for mix with flatMap
or map
is not readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With