这个例外在Scala中意味着什么:
java.util.NoSuchElementException: Predicate does not hold for ...
Run Code Online (Sandbox Code Playgroud)
这可能导致的一种方法是,如果你有一个将Try与谓词(if
语句)结合起来的for-comprehension :
for {
x <- Try(expr) if booleanExpr
} {
...
}
Run Code Online (Sandbox Code Playgroud)
filter
Try 的方法可以抛出java.util.NoSuchElementException以跳过循环体,如果booleanExpr
求值为false
.
该reason
例外的领域是"谓词不适用于......"
正如@Guillaume在评论中指出的那样,Try的实现通过它实现的方式导致了这一点filter
- 编译器在你使用条件(if)时调用的方法for comprehension
:
if (p(value)) this
else Failure(new NoSuchElementException("Predicate does not hold for " + value))
Run Code Online (Sandbox Code Playgroud)
它特定于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:
Run Code Online (Sandbox Code Playgroud)