Scala:Predicate没有Exception

aut*_*hic 7 for-loop scala

这个例外在Scala中意味着什么:

java.util.NoSuchElementException: Predicate does not hold for ...
Run Code Online (Sandbox Code Playgroud)

Bre*_*ust 7

这可能导致的一种方法是,如果你有一个将Try与谓词(if语句)结合起来的for-comprehension :

for {
  x <- Try(expr) if booleanExpr
} {
  ...
}
Run Code Online (Sandbox Code Playgroud)

filterTry 的方法可以抛出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)

  • @Aivean https://github.com/scala/scala/blob/2.11.x/src/library/scala/util/Try.scala#L241 (2认同)

Gui*_*ssé 5

它特定于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)