Home > OS >  Scala "does not contain" with String split
Scala "does not contain" with String split

Time:03-16

I am trying Scala for the very first time, not sure how to filter based on not contains. I have a below query;

.filter(_.get[Option[String]]("status") map(_ split "," contains "Pending") getOrElse(false))

But I want to do something like below;

.filter(_.get[Option[String]]("status") map(_ split "," does not contain "Pending") getOrElse(false))

Can someone please help?

CodePudding user response:

Figured out the solution;

.filter(_.get[Option[String]]("status") map(a => !(a split "," contains "Pending")) getOrElse(false))

Thanks.

CodePudding user response:

You can use exists and forall to simplify this. These functions return true if a condition is true for any or all elements of a collection.

So the pattern

Option[String].map(???).getOrElse(false)

can be

Option[String].exists(???)

And the condition

!(a split "," contains "Pending")

can be

a.split(",").forall(_ != "Pending")

Applying both of these to the original code gives

.filter(_.get[Option[String]]("status").exists(_.split(",").forall(_ != "Pending")))

But I would recommend a local function to clarify this code:

def notPending(s: String) = s.split(",").forall(_ != "Pending")

.filter(_.get[Option[String]]("status").exists(notPending))

This reads as "take all values where the status option exists and the status is not pending"

  • Related