What does this exception mean in Scala:
java.util.NoSuchElementException: Predicate does not hold for ...
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))
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:
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