[英]Scala-Declaring variables when using Try,Success and Failure for error handling?
The context of my problem is the following: 我的问题的背景如下:
I'm trying to apply a linear regression model to some data but the model will throw an Exception error if the data is not presented in the required format. 我正在尝试将线性回归模型应用于某些数据,但是如果未按要求的格式显示数据,则该模型将引发Exception错误。 If successful, then I want to save the residuals of the output as a new variable, but if failure then I want to define an array of zeroes instead as the new variable. 如果成功,那么我想将输出的残差另存为新变量,但是如果失败,那么我想将零数组定义为新变量。
My problem is that I'm not being able to declare this variable depending on the success or failure of the function. 我的问题是我无法根据函数的成功或失败来声明此变量。
More specifically, the model is called as follows: 更具体地说,该模型的调用如下:
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression
import org.apache.commons.math3.stat.regression.AbstractMultipleLinearRegression
import scala.util.{Try,Success,Failure}
val model=new OLSMultipleLinearRegression()
val goodData=Array(Array(.1),Array(.2))
val badData=Array(Array(.1,.1),Array(.2,.2))
val y=Array(.5,.6)
The following yields the exception error MathIllegalArgumentException
以下产生异常错误MathIllegalArgumentException
model.newSampleData(y,badData)
but this yields the normal behavior 但这产生了正常的行为
model.newSampleData(y,goodData)
If there is an exception error then I want to declare the variable val params=Array.fill(2)(0.0)
but if there is no exception error then I want to declare the variable val params=model.estimateResiduals()
. 如果存在异常错误,那么我想声明变量val params=Array.fill(2)(0.0)
但是如果没有异常错误,那么我想声明变量val params=model.estimateResiduals()
。
My attempt (using Try
, Success
and Failure
) is: 我的尝试(使用Try
, Success
和Failure
)是:
Try{model.newSampleData(y,badData)} match {
case Success(_)=>val params=model.estimateResiduals()
case Failure(_)=>val params=Array.fill(2)(0.0)
}
but when I type params
I get the error error: not found: value params
. 但是当我输入params
时,出现error: not found: value params
。
How can I declare the variable params
given the success or failure of the linear regression method? 给定线性回归方法的成功或失败,如何声明变量params
?
Variables you declare are local to the block. 您声明的变量是该块的局部变量。 Use 采用
val params = Try{model.newSampleData(y,badData)} match {
case Success(_) => model.estimateResiduals()
case Failure(_) => Array.fill(2)(0.0)
}
or just 要不就
val params = Try(model.newSampleData(y,badData))
.map(_ => model.estimateResiduals())
.getOrElse(Array.fill(2)(0.0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.