我无法理解为什么recover返回为空成功以及过滤器的条件不满足
case class Account(acctNum: Int, balance: Double, interestRace: Double)
def getAccount()={
Account(111,7000.0,1.2)
}
val withdrowal = 1500
val acc = Try(getAccount())
val withdrowalResult = acc map {
(x: Account) => Account(x.acctNum, x.balance-withdrowal,x.interestRace)
} filter{
(x: Account) => x.balance>8000
}recover{
case nsee: NoSuchElementException => println("Something went wrong")
}
println(withdrowalResult)
如果我打印withdrawarResult,我会得到
Success(())
如果我的条件不满意,我该怎么办?如果我只是想得到失败并照顾异常?
答案 0 :(得分:2)
您使用了恢复并恢复了失败成功。鉴于您只是在恢复中打印并且没有产生任何结果,因此您将获得成功[单位](单位是println的结果)。
....filter(x => x.balance > 8000)
.recover { case nsee: NoSuchElementException => "Not empty" }
// res4: scala.util.Try[java.io.Serializable] = Success(Not empty)
如果你想要失败,就不要做恢复:
val withdrowalResult = acc map {
(x: Account) => Account(x.acctNum, x.balance-withdrowal,x.interestRace)
} filter {
(x: Account) => x.balance>8000
}
// Failure(java.util.NoSuchElementException: Predicate does not hold for Account(111,5500.0,1.2))