automorphic
automorphic

Reputation: 800

Scala: Predicate does not hold Exception

What does this exception mean in Scala:

java.util.NoSuchElementException: Predicate does not hold for ...

Upvotes: 8

Views: 2534

Answers (2)

Brent Faust
Brent Faust

Reputation: 9309

One way this can be caused is if you have a for-comprehension that combines a Try with a predicate (if statement):

for {
  x <- Try(expr) if booleanExpr
} {
  ...
}

The filter method of Try can throw a java.util.NoSuchElementException to skip the loop body if booleanExpr evaluates to false.

The reason field of that exception is "Predicate does not hold for ..."

As @Guillaume points out in the comments, it's the implementation of Try that causes this by the way it implements filter -- the method that's called by the compiler when you use a conditional (if) within a for comprehension:

if (p(value)) this
else Failure(new NoSuchElementException("Predicate does not hold for " + value))

Upvotes: 7

Guillaume Mass&#233;
Guillaume Mass&#233;

Reputation: 8064

It's specific to scala.util.Try

scala.util.Try(2).filter(_ < 0) // Failure(java.util.NoSuchElementException: Predicate does not hold for 2)



  for {
    v <- scala.util.Try(2)
    if v < 0
  } yield v // Failure(java.util.NoSuchElementException: 

Upvotes: 6

Related Questions