Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Predicate does not hold Exception

Tags:

for-loop

scala

What does this exception mean in Scala:

java.util.NoSuchElementException: Predicate does not hold for ...
like image 997
automorphic Avatar asked Sep 24 '15 02:09

automorphic


2 Answers

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))
like image 200
Brent Faust Avatar answered Nov 14 '22 22:11

Brent Faust


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: 
like image 42
Guillaume Massé Avatar answered Nov 14 '22 23:11

Guillaume Massé