HHH
HHH

Reputation: 6485

How to make sure an Option field in Scala is not None

I have a list consisting of case classes with the following signature

case class Post(Id: Option[String], Type: Option[String], CreationDate: Option[String], Tags: Option[String])

when processing the elements of this list, how can I check and make sure that the fields have values and are not None?

Upvotes: 2

Views: 1265

Answers (2)

elm
elm

Reputation: 20415

Given a case class, you can iterate over its values, and require for each to hold a condition; hence

myPosts.forall( _.productIterator.forall( _ != None ))

requires each post in the list and for each value, no one is None.

Upvotes: 0

Pim Verkerk
Pim Verkerk

Reputation: 1066

val posts: List[Post] = ???

def isCompletePost(p: Post): Boolean = p match {
  case Post(Some(_), Some(_), Some(_), Some(_)) => true
  case _                                        => false
}

val completePosts = posts filter isCompletePost

Upvotes: 4

Related Questions