Scala: predicate contains no exception

What does this exception mean in Scala:

java.util.NoSuchElementException: Predicate does not hold for ... 
+5
source share
2 answers

It is 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: 
+4
source

One way can be called if you have an understanding that combines Try with a predicate ( if statement):

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

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

The reason field for this exception is: "The predicate is not executed for ..."

As @Guillaume notes in the comments, the Try implementation that calls this method implements a filter - a method that the compiler calls when using a conditional (if) within for comprehension

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

Source: https://habr.com/ru/post/1232159/


All Articles